Okay so I am trying to make a game of sticks with python. I am asking the user the amount of sticks for him to input.
I am supposed to include a condition where if the user does input a number between 10 and 100, it will ask him over and over again until he gives in a number between that amount. However, my code ends whenever I do input a number between that such amount.
Also, my initial problem is how to ask the player how many sticks will they take after they select the like amount. It just repeats back to the same question, asking them how many sticks do they wish to have in the game. My initial problem is how to advance to the next part.
print("Welcome to the game of sticks, choose wisely...")
sticks = int(input("Choose the number of sticks(10-100 ): "))
while(sticks >= 10 and sticks <= 100 ):
print("There are %d sticks on the board." % sticks)
sticks = int(input("Choose the number of sticks(10-100 ): "))
take = int(input("How many sticks will you take?(1-3): "))
while(take >= 1 and take <= 3):
print(sticks - take)
take = int(input("How many sticks will you take?(1-3): "))
Does anyone have any familiarity with programming a sticks game? Please don't give me the whole output, just tell me what's wrong. What should I do to make it work?
On this line you test if sticks is a valid number and if it is you stay in the while loop. This seems to be your logic error. You are essentially staying in your while loop when you enter a valid number when you want it the other way around.
#your code
while(sticks >= 10 and sticks <= 100 ):
print("There are %d sticks on the board." % sticks)
sticks = int(input("Choose the number of sticks(10-100 ): "))
in the example below you test if the input is valid and if it is you don't enter the loop. If the input isn't valid you stay in the loop until a valid number is entered.
#updated code
while(sticks < 10 or sticks > 100 ):
print("There are %d sticks on the board." % sticks)
sticks = int(input("Choose the number of sticks(10-100 ): "))
Your first while asks how many sticks you want. you need an if statement that says if the number is acceptable, break, else, do it again.
The second while loop asks how many to take out. It shouldn't repeat. Try using if else statements
You use break
Try This:
https://wiki.python.org/moin/WhileLoop
For example
while(sticks >= 10 and sticks <= 100 ):
print("There are %d sticks on the board." % sticks)
sticks = int(input("Choose the number of sticks(10-100 ): "))
break
take = int(input("How many sticks will you take?(1-3): "))
while(take >= 1 and take <= 3):
print(sticks - take)
take = int(input("How many sticks will you take?(1-3): "))
break
Related
Q-> WAP in python to take input of different numbers from the user if the number if less than 100 keep on taking the input from the user and if the number entered is bigger than 100 display the message "congratulations! The number you entered is bigger than 100". We have to do this using for loop. The program that I wrote is:
a=list(input("enter a number"))
for a1 in a:
a=int(input())
if int(a1)<100:
print("try again")
continue
else:
print("congratulation the number you entered is more than 100")
break
but this program is faulty. How can I write the correct code?
You don't need to build a list, since there's nothing you need the old numbers for. The most straightforward way to do this would be a while loop, e.g.:
while int(input("enter a number ")) < 100:
print("try again")
print("congratulations! the number you entered is at least 100")
Using a for loop doesn't make as much sense because you don't have a set number of things to iterate over; you need to just keep retrying while the user is entering number that's too small. If I had to use for here, though, I'd use something like itertools.count:
from itertools import count
for _ in count():
if int(input("enter a number ")) >= 100:
print("congratulations!")
break
print("try again")
Code:-
for _ in iter(int, 1):
a=input("Enter the number: ")
if int(a)>100:
print("Congratulation")
break
print("Your number is lower")
Output:-
Enter the number: 80
Your number is lower
Enter the number: 43
Your number is lower
Enter the number: 89
Your number is lower
Enter the number: 97
Your number is lower
Enter the number: 101
Congratulation
Python beginner here. Practicing user input control.
Trying to make user input loop to the beginning if anything but a whole number between 1 and 10 is used. Been trying for hours, tried using Try and Except commands but couldn't do it correctly. What am i doing wrong? Thank you.
Edit:
Thank you very much for your help everyone, however the problem is still not solved (but very close!) I'm trying to figure out how to loop back to the beginning if anything BUT a whole number is typed. Agent Biscuit (above) gave a great answer for floating numbers, but any word or letter that is typed still produces an error. I´m trying to understand how to loop when anything random (except whole numbers between 1 and 10) is typed. None of the above examples produced corrcct results. Thank you for your help
while True:
print("Enter a number between 1 and 10")
number = int(input())
if (number > 0) and (number < 10):
print("Thank you, the end.")
break
else number != (> 0 and < 10):
print("It has to be a whole number between 1 and 10.")
print("Please try again:")
I have identified some problems.
First, the input statement you are using would just raise an error if a float value is entered, because the int at the start requires all elements of the input to be a number, and . is not a number.
Second; your else statement. else is just left as else:, and takes no arguments or parameters afterwards.
Now, how to check if the number is not whole? Try this:
while True:
print("Enter a number between 1 and 10")
number = float(input())
if (number > 0) and (number < 10) and (round(number)==number):
print("Thank you, the end.")
break
else:
print("It has to be a whole number between 1 and 10.")
print("Please try again:")
This accepts a float value, but only accepts it if it is equal to a whole number, hence the (round(number)==number).
Hope that answers your question.
First of all, you can't use a condition in a else statement. Also, you need to use or operator instead of and if one of the conditions is acceptable.
So, your code needs to be like this
while True:
print("Enter a number between 1 and 10")
number = int(input())
if (number > 0) and (number < 10):
print("Thank you, the end.")
break
elif number < 0 or number >10:
print("It has to be a whole number between 1 and 10.")
print("Please try again:")
Thanks to ack (above) for pointing me to a useful link. By studying another thread, I found the solution. It may not be perfect code, but it works 100%:
while True:
try:
print("Enter a number between 1 and 10")
number = float(input())
if (number > 0) and (number < 10) and (round(number)==number):
print("Thank you, the end.")
break
else:
print("\n")
print("It has to be a whole number between 1 and 10.")
print("Please try again:")
print("\n")
continue
except ValueError:
print("It has to be a whole number between 1 and 10.")
print("Please try again:")
print("\n")
I'm having an issue with my program. I'm working on a program that lets you play a small game of guessing the correct number. The problem is if you guess the correct number it will not print out: "You guessed it correctly". The program will not continue and will stay stuck on the correct number. This only happens if you have to guess multiple times. I've tried changing the else to a break command but it didn't work.
Is there anyone with a suggestion?
This is what I use to test it:
smallest number: 1
biggest number: 10
how many times can u guess: 10
If you try to guess the correct number two or three times (maybe more if u need more guesses) it will not print out you won.
import random
#counts the mistakes
count = 1
#askes to give up a minimum and maximum to guess between
minimum = int(input("what is the smallest number? "))
maximum = int(input("what is the biggest number? "))
#askes how many times u can guess in total
amount = int(input("How many times can you guess? "))
#random number between the 2 variables minimum and maximum
x = random.randrange(minimum, maximum)
guess = int(input("guess the number: "))
#while loop until the guess is the same as the random number
while guess != x:
#this is if u guessed to much u get the error that you've guessed to much
while count < amount:
if guess > x:
print("this is not the correct number, the correct number is lower \n")
guess = int(input("guess the number: "))
count += 1
elif guess < x:
print("this is not the correct number, the correct number is higher \n")
guess = int(input("guess the number: "))
count += 1
else: print("\n \nYou Lost, You've guessed", x, "times\n")
break
#this part is not working, only if you guess it at the first time. it should also print this if you guessed it in 3 times
else: print("You guessed it correctly", x)
test = (input("this is just a test if it continues out of the loop "))
print(test)
The main issue is that once guess == x and count < amount you have a while loop running that will never stop, since you don't take new inputs. At that point, you should break out of the loop, which will also conclude the outer loop
You can do it simply by using one while loop as follows:
import random
#counts the mistakes
count = 1
#askes to give up a minimum and maximum to guess between
minimum = int(input("what is the smallest number? "))
maximum = int(input("what is the biggest number? "))
#askes how many times u can guess in total
amount = int(input("How many times can you guess? "))
#random number between the 2 variables minimum and maximum
x = random.randrange(minimum, maximum)
#this is if u guessed too much u get the error that you've guessed too much
while count <= amount:
guess = int(input("guess the number: "))
if guess > x:
print("this is not the correct number, the correct number is lower \n")
count += 1
elif guess < x:
print("this is not the correct number, the correct number is higher \n")
count += 1
else:
print("You guessed it correctly", x)
break
if guess!=x:
print("\n \nYou Lost, You've guessed", count, "times\n")
As Lukas says, you've kind of created a situation where you get into a loop you can never escape because you don't ask again.
One common pattern you could try is to deliberately make a while loop that will run and run, until you explicitly break out of it (either because the player has guessed too many times, or because they guessed correctly). Also, you can get away with only asking for a guess in one part of your code, inside that while loop, rather than in a few places.
Here's my tweak to your code - one of lots of ways of doing what you want to:
import random
#counts the mistakes
count = 0
#asks to give up a minimum and maximum to guess between
minimum = int(input("what is the smallest number? "))
maximum = int(input("what is the biggest number? "))
#asks how many times u can guess in total
amount = int(input("How many times can you guess? "))
#random number between the 2 variables minimum and maximum
x = random.randrange(minimum, maximum)
#while loop until the guess is the same as the random number
while True:
if count < amount:
guess = int(input("guess the number: "))
#this is if u guessed to much u get the error that you've guessed to much
if guess > x:
print("this is not the correct number, the correct number is lower \n")
count += 1
elif guess < x:
print("this is not the correct number, the correct number is higher \n")
count += 1
else:
print("You guessed it correctly", x)
break
else:
print("\n \nYou Lost, You've guessed", x, "times\n")
PS: You got pretty close to making it work, so nice one for getting as far as you did!
This condition is never checked again when the guessed number is correct so the program hangs:
while guess != x:
How about you check for equality as the first condition and break out of the loop if true:
import random
#counts the mistakes
count = 1
#askes to give up a minimum and maximum to guess between
minimum = int(input("what is the smallest number? "))
maximum = int(input("what is the biggest number? "))
#askes how many times u can guess in total
amount = int(input("How many times can you guess? "))
#random number between the 2 variables minimum and maximum
x = random.randrange(minimum, maximum)
guess = int(input("guess the number: "))
if guess == x:
print("You guessed it correctly", x)
else:
while count < amount:
if guess > x:
print("this is not the correct number, the correct number is lower \n")
guess = int(input("guess the number: "))
count += 1
elif guess < x:
print("this is not the correct number, the correct number is higher \n")
guess = int(input("guess the number: "))
count += 1
else:
print("You guessed it correctly", x)
break
else:
print("You guessed too many times")
I'm beginning to learn python and I've just finished my first project, which was the collatz sequence, which is "If n is even, divide it by 2 to get n / 2. If n is odd, multiply it by 3 and add 1 to obtain 3n + 1. Repeat the process until you reach 1."
Here is my code, it's not very long:
import sys
def integer(): #Asks for input and checks whether positive integer
while True:
number = input("Enter a positive, whole number:")
try:
number = int(number)
if number > 0:
break
else:
raise ValueError
except ValueError:
print("That's not right! \n Please enter a positive, whole number")
return number
number = None
def collatz():
global number
print(number)
while number > 1:
if number % 2 ==0:
number = number // 2
else:
number = number * 3 + 1
print(number)
while True: #loop so that you can try again
number = integer()
collatz()
repeat = input("Try again? Y/N").upper()
while repeat != "Y" and repeat != "N": #Only Y/N are valid
repeat = input("Try again? Y/N")
if repeat == "N":
sys.exit() #end program if N selected
else:
pass #Reloops to try again
I ran this code on an app called "QPython3" on my Google Pixel XL (Up to 2.4 GHz), running Android 7.1.1 and also my base model MacBook Pro (Retina, 13-inch, Early 2015)(2.7GHz).
The MacBook took multiple minutes to reach 1 when I used an absurdly large number such as 10^100, but my phone did it almost instantaneously.
I don't understand why this would be the case. Shouldn't the proper computer be better in every way?
(If you want to give feedback on the overall effectiveness of my code, that is appreciated, but probably not worth your time as I'm very new and would likely not understand things too well. I'm just trying to make code that works at this stage)
I have a quick question.
I want to make my number guessing game tell the user if they are 2 numbers away from guessing the random number.
I do not want the program to say how many numbers away the user is.
The way I'm thinking is this. I just can't put this into proper code.
Random_number = 5
guess = 3
print('you are close to guessing the number!')
guess = 7
print('you are close to guessing the number!')
guess = 2 #more than 2 away from the number
print('you are NOT close to guessing the number')
I am going to start by saying my python is rusty and someone please fix it if im off alittle.
All you need to do if use an if statement.
random = 5
guess = 3
if( guess == random ):
print('your right!')
elif ( abs (guess - random) <= 2 ):
print('you are close to guessing the number!')
else:
print('you are not close enough!')
Edited the elseif logic according to #9000's suggestion.
Try this:
for number in range (2):
if guess == Random_number:
print('you guessed the number!')
if guess - number == Random_number or guess + number == Random_number:
print('you are close to guessing the number!)
Here is the explanation. The first line is saying "for the numbers in the range of 0 to 2 set number equal to that number." So the next if part will run 3 times: for number equaling 0, 1, and 2. So, if your guess is within 2 of the random number, it will print you are close to the random number. If you have the correct guess, it will obviously print you guessed it correctly.