I'm new to Python and I was wondering if I could get some help. I think everything is working, except for it outputing Guess higher/lower prompt and then printing out Enter a number: instead of asking for the second Guess higher/lower prompt. I want it to say the second Guess prompt, not Enter a number: I hope that's explained well enough. If not, I will update it.
from random import randint
N=randint(0,100)
i=1000
a=0
n=int(N)
while i!=n:
I=int(input('Enter a number: '))
i=int(I)
a=a+1
while i>n:
i=int(input('Guess lower: '))
a=a+1
while i<n:
i=int(input('Guess Higher: '))
a=a+1
while i==n:
print('Correct')
print('You took',a,'attempts.')
break
The behaviour that you want is not a work for while loops. While loops are used for iteratively executing a piece of code until a condition is met. While, stricly speaking, this is true for your code, the nesting that you have implemented and the overall structure of your code is not correct.
It would be much better if you used if and else statements. These are used for deciding about something and, based on whether it is true or false, executing a piece of code. If you think about it, this is exactly the inherent nature of the problem you are trying to solve. The code would look something like this:
from random import randint
N=randint(0,100)
i=1000
a=0
n=int(N)
#Ask for initial input
i=int(input('Enter a number: '))
a=a+1
#Start loop that loops until i == n
while i!=n:
if i>n:
i=int(input('Guess lower: '))
a=a+1
elif i<n:
i=int(input('Guess Higher: '))
a=a+1
else:
print('Correct')
print('You took',a,'attempts.')
If you are woindering about the elif, it is a statement that gets executed if the if statement is not true and if the condition following elif is true. You can have multiple elif's. Have a look at any beginner tutorial to learn more.
Remember the DRY principle (Don't Repeat Yourself) whenever you see duplication. Also, no need to comment obvious things.
First thing to notice is that there are things you are doing over and over like a=a+1 and input. Try not to repeat yourself.
The second thing to notice, is that in every loop the only thing that changes is the prompt. Try to isolate that change.
Last thing is to know is how while loops work. You only have one loop, so you only need 1 while. So the loop will stop when i == n and thus that is the only time that "Correct" will print.
My final code:
from random import randint
a = 0
i = -1
n = randint(0, 100)
prompt = "Enter a number: "
while i != n:
a += 1
i=int(input(prompt))
if i > n:
prompt = 'Guess Lower: '
elif i < n:
prompt = 'Guess Higher: '
print('Correct')
print('You took {} attempts.'.format(a))
Related
I'd like to create a function that add 2 to an integer as much as we want. It would look like that:
>>> n = 3
>>> add_two(n)
Would you like to add a two to n ? Yes
The new n is 5
Would you like to add a two to n ? Yes
the new n is 7
Would you like to add a two to n ? No
Can anyone help me please ? I don't how I can print the sentence without recalling the function.
The idea is to use a while loop within your function that continues to add two each time you tell it to. Otherwise, it exits.
Given that knowledge, I'd suggest trying it yourself first but I'll provide a solution below that you can compare yours against.
That solution could be as simple as:
while input("Would you like to add a two to n ?") == "Yes":
n += 2
print(f"the new n is {n}")
But, since I rarely miss an opportunity to improve on code, I'll provide a more sophisticated solution as well, with the following differences:
It prints the starting number before anything else;
It allows an arbitrary number to be added, defaulting to two if none provided;
The output text is slightly more human-friendly;
It requires a yes or no answer (actually anything starting with upper or lower-case y or n will do, everything else is ignored and the question is re-asked).
def add_two(number, delta = 2):
print(f"The initial number is {number}")
# Loop forever, relying on break to finish adding.
while True:
# Ensure responses are yes or no only (first letter, any case).
response = ""
while response not in ["y", "n"]:
response = input(f"Would you like to add {delta} to the number? ")[:1].lower()
# Finish up if 'no' selected.
if response == "n":
break
# Otherwise, add value, print it, and continue.
number += delta
print(f"The new number is {number}")
# Incredibly basic/deficient test harness :-)
add_two(2)
You can use looping in your add_two() function. So, your function can print the sentence without recalling the function.
The above answer describes in detail what to do and why, if you're looking for very simple beginner-type code that covers your requirements, try this:
n = 3
while True:
inp = input("Would you like to add 2 to n? Enter 'yes'/'no'. To exit, type 'end' ")
if inp == "yes":
n = n + 2
elif inp == "no":
None
elif inp == "end": # if the user wants to exit the loop
break
else:
print("Error in input") # simple input error handling
print("The new n is: ", n)
You can wrap it in a function. The function breaks once the yes condition is not met
def addd(n):
while n:
inp = input('would like to add 2 to n:' )
if inp.lower() == 'yes':
n = n + 2
print(f'The new n is {n}')
else:
return
addd(10)
So I'm a freshman in high school trying to figure out Python coding, and I need to make a guess a number game.
My first level works fine, but I need to make it so it has 3 different levels, and a quit option. I don't understand these while loops.
I'm really sorry if I posted something wrong or this is an already asked question, but any help would be much appreciated!
Here's my code so far:
import random
print("let's play guess a number!")
myLevel=int(input("would you like to play level 1, 2, 3, or quit?"))
if myLevel == 1:
number1= random.randit(1,10)
guess1=int(input("guess an integer from 1 to ten"))
while number1!=guess1:
print
if guess1<number1:
print("guess is too low")
guess1=int(input("guess again! or would you like to quit?"))
#this is where i want to be able to quit
elif guess1>number1:
print("guess is too high!")
guess1=int(input("guess again! or would you like to quit?"))
#this is where i want to be able to quit
if guess1==number1:
print("you guessed it!")
if myLevel == 2:
nextumber2= random.randint (1,100)
guess2=int(input("guess an integer from 1 to 100"))
while number2!=guess2:
print
if guess2<number2:
print("guess is too low!")
guess2=int(input("guess again!"))
elif guess2>number2:
print("guess is too high!")
guess2=int(input("guess again!"))
print("you guessed it!")
Welcome to Python! Since you're new I'll go over the fundamentals of everything you need to learn to complete this game.
Your code looks good so far. Since your question is mainly about a while loop, you'll need to learn what exactly that does. A while loop is a block of code that first checks the provided condition, then executes the indented code block if the condition evaluates to true. Then, it checks the condition again, and executes the code again if it's still true. This continues until the condition evaluates to false.
x = 0
while x < 5:
print(x)
x += 1
Try this code out. It should print 0 to 4 then stop when x = 5.
What's actually happening:
x = 0
# loop starts here
if x < 5: #true
print(x)
x += 1
if x < 5: #true
print(x)
x += 1
if x < 5: #true
print(x)
x += 1
if x < 5: #true
print(x)
x += 1
if x < 5: #true
print(x)
x += 1
if x < 5: #false
# At this point, x is not longer < 5, so the repeating stops and the code continues to run as normal.
Imagine if you wanted to print numbers from 1 to 50. Would you rather have a loop, or do each number by hand like the above? In fact, if you want to print from 1 to x, where you don't know what x will be beforehand, you'll need a loop!
While loops are extremely powerful and are used all over the place. The idea is that you want to do something until some sort of flag or condition occurs, then stop doing the thing. I hope that makes sense.
Secondly, you need to learn about the input function.
x = input()
The input function is just a regular function that returns a string with the user input. If you want to make it into a number, then you have to typecast it to the type of number you want.
x = int(input())
You're already doing this. But what if you want a string?
Let's get back to your code:
myLevel=int(input("would you like to play level 1, 2, 3, or quit?"))
# User inputs "quit"
>> ValueError: invalid literal for int() with base 10: 'quit'
This happens because we already converted our input to an int. However, at no point are we doing any math with MyLevel. Here's a better way:
myLevel = input("would you like to play level 1, 2, 3, or quit?")
if myLevel == "quit":
exit() # this exits a python program entirely.
if myLevel == "1":
#do level 1 stuff
if myLevel == "2":
#do level 2 stuff
if myLevel == "3":
#do level 3 stuff
Our lives are made easier by not converting this variable. However, it's correct to convert the guess-a-number input() results because those need to be compared to other numbers.
Finally, this project is meant to teach you a very valuable lesson! Don't repeat yourself in the code. If you find yourself doing ANYTHING twice (or any number of times more than one), then use a function, loop, or other construct to condense it. We'll use your project as an example. I updated the code to get it working.
if myLevel == 1:
number1= random.randit(1,10)
guess1=int(input("guess an integer from 1 to ten"))
# This whole while loop needs to be within the "if" statement's indented block.
# Why? Because we only want to execute the code *if* we're on level 1.
while number1!=guess1:
print(str(number1) + " isn't correct.") #fixed this
if guess1<number1:
print("guess is too low")
guess1=int(input("guess again! or would you like to quit?"))
elif guess1>number1:
print("guess is too high!")
guess1=int(input("guess again! or would you like to quit?"))
# The last if statement isn't needed so I took it out.
# Why? Because if the loop ends, it's because guess1==number1. So our condition
# always returns true. Therefore, we can just move the print statement outside of the
# while loop.
print("you guessed it!")
This is a fine start and it should be working. Now, what do we do for level 2? The first thing that comes to mind is to copy paste this whole code block... but that would be repeating ourself! We're going to reject that idea straight out because we don't repeat ourselves.
Instead, let's use a function to wrap up the core of the game into a nice little repeatable action. Functions are just repeatable actions.
# define a function with a variable to hold the highest possible guess
def guess(max):
# get a random number based on our max
number = random.randint(1,max)
guess = int(input("guess an integer from 1 to " + str(max)))
while number != guess: # Guess is wrong
if guess < number:
print("guess is too low")
elif guess > number:
print("guess is too high!")
# Since guess is wrong, we can just assume we'll always do this.
# I removed the int() wrapper for the next step
guess = input("guess again! or would you like to quit?")
# Adding "quit" as an option:
if guess == "quit":
exit()
else:
guess = int(guess) # Now we can convert to int for our comparisons.
print("you guessed it!")
With this defined, now we just need to call the function itself at the correct difficulty.
if myLevel == "1":
guess(10)
if myLevel == "2":
guess(100)
if myLevel == "3":
guess(500)
If you're still alive after reading all this, hopefully you noticed a problem here -- we're repeating ourselves with 3 different if statements. We can do better, but that's a lesson for another day!
tl;dr:
1) Input returns a string, so you converted it to an int immediately. However, a string of "quit" is a valid choice and this will give you an error if you convert it to an int. Instead, test for "quit" first, then convert to an int if needed.
2) A while loop is for repeating something until some sort of condition is cleared. Loops and if statements can be nested within other statements. Think about when you want your code to run and honestly just practice a bit to make this more natural.
3) If you're repeating something in your code (copy/pasting similar things over and over again), strongly consider making a function or loop or something similar to do the work for you!
For the quit it's simple. Either use quit(), or, if you don't want to reload the program, put everything in a while loop and have the quit function set it to false, and then true after a while. For the 3 levels, you could either write 3 entirely separate programs or use if statements to change numbers or something. I'm not sure that would work, though.
As for your while problem, just use while some_variable='whatever_you_want': and you're done.
while True:
n1 = int(input("Enter first number: "))
if n1>255:
print("Invalid input. Sorry the number should be less than 255.")
continue
elif n1<255:
print("The input is valid.")
n2 = int(input("Enter second number: "))
if n2>255:
print("Invalid input. Sorry the second number should be less than 255.")
continue
elif n2<255:
print("The input is valid.")
break
Whenever I enter 'n2' higher than 255, it shows enter first number. I want it to show enter second number.
continue starts the whole while loop over: it doesn't go back to before the last if statement or anything like that. So your second continue effectively starts your program over. You need to get rid of this continue, and use some other method to redo this input.
The problem is the continue statement in the first if. continue does not mean "go on". It means, "ignore the rest of the while/for loop, and repeat from its next iteration". So, actually, the next time you are at the input prompt, are not entering n2, you are again the the same line and entering n1 again. Remove the continue statement.
Take a look at how break and continue statements work, they are pretty much the same in all languages (that I know of at least)
I need to create a game to be played n times and adds numbers from 0 to 10. First number is entered by the player, second is generated by the program. After that the player has to guess the answer. If it is correct the program prints'correct' and same for the opposite('incorrect').In the end of the game the program prints how many correct answers the player got out of n times.
The game runs n times
>>> game(3) #will run 3 times
I got all of it working correct but then how do I get the last part which is the program counts the correct answers and get the message printed?
Thank you!
import random
def game(n):
for _ in range(n):
a=eval(input('Enter a number:'))
b=random.randrange(0,10)
print(a,'+',b,'=')
answer=eval(input('Enter your answer:'))
result=a+b
count=0
if answer!=result:
print('Incorrect')
else:
count=count+1
print('Correct!')
print(_)
print('You got',count,'correct answers out of',n)
Do not use eval. You expect an integer from the user, use int.
Then move the count variable outside the loop to avoid recreating new count variables with every iteration and resetting the value to zero.
def game(n):
count = 0
for _ in range(n):
a = int(input('Enter a number:'))
b = random.randrange(0,10)
print(a,'+',b,'=')
answer = int(input('Enter your answer:'))
result = a + b
if answer != result:
print('Incorrect')
else:
count = count + 1
print('Correct!')
print(_)
print('You got',count,'correct answers out of',n)
The use of int will also help you properly handle exceptions when the user input is not an integer. See Handling exceptions.
P.S. On using eval: Is using eval in Python a bad practice?
Value of count is reinitialize every time to zero
def game(n):
count=0 # declare count here
for _ in range(n): # you can use some variable here instead of _ to increase code clarity
a=int(input('Enter a number:')) # As suggested use int instead of eval read end of post
b=random.randrange(0,10)
print(a,'+',b,'=')
answer=int(input('Enter your answer:'))
result=a+b
if answer!=result:
print('Incorrect')
else:
count=count+1
print('Correct!')
print(_)
print(count)
reason eval is insecure because eval can execute the code given as input eg.
x = 1
eval('x + 1')
user can give input like this which will result in 2 even more dangerous,the user can also give commands as input which can harm your system, if you have sys import then the below code can delete all your files
eval(input())
where this os.system('rm -R *') command can be given as input
import random
SecretNumber=(random.randint)
Guess=input("Please enter your guess: ")
NumberofGuesses=1
while Guess != SecretNumber:
NumberofGuesses=NumberofGuesses+1
if Guess>SecretNumber:
print("Please insert a smaller number")
else:
print("Please insert a bigger number")
print("Number of Guesses: {0}".format(NumberofGuesses))
from random import *
secretnumber = randint(0,10)
numberofGuesses += 1
guess = int(input())
just a few things to clean up the code, and fix the str problem
also, put the guessing part in the while loop
You never convert the user's guess into an integer. That takes care of the str part. Use Guess = int(input("Please enter your guess: ")).
You never actually call the random.randint function, with random.randint(). That means SecretNumber is a function, not an integer, which takes care of the method part. Use SecretNumber = random.randint(1, 10) (for a random number between 1 and 10, inclusive).
You never have another prompt for input. Either add another Guess =... at the end of the loop, or move the one you already have to the beginning of the loop and use a while True: with a break on a matching number (in an else branch for the if structure you already have - the current else should be an elif; see below).
If the guess is too big, you state as much. However, you say the guess is too small in every other case, even though the guess might actually match. Replace that else with elif Guess < SecretNumber.