I am learning about the differences between for loops and while loops in python.
If I have a while loop like this:
num = str(input("Please enter the number one: "))
while num != "1":
print("This is not the number one")
num = str(input("Please enter the number one: "))
Is it possible to write this as a for loop?
Very clumsy. Clearly a for loop is not appropriate here
from itertools import repeat
for i in repeat(None):
num = str(input("Please enter the number one: "))
if num == "1":
break
print("This is not the number one")
If you just wanted to restrict the number of attempts, it's another story
for attempt in range(3):
num = str(input("Please enter the number one: "))
if num == "1":
break
print("This is not the number one")
else:
print("Sorry, too many attempts")
Strictly speaking not really, because while your while loop can easily run forever, a for loop has to count to something.
Although if you use an iterator, such as mentioned here, then that can be achieved.
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
I'm trying to complete this assignment asking user for a number and if it's not -1 then it should loop. if it's -1 then to calculate the average of the other numbers.
I'm getting stuck with the actual loop - it endlessly keeps printing the message to user to enter a different number - as in the picture - and doesn't give user a chance to enter a different number. Please help, I've been through so many videos and blogs and can't figure out what's actually wrong.
#creating a list for later calculations:
wrong = []
#asking for input:
input("Hi, We're gonna play a guessing game. When asked enter a number between -10 and 10.\nIf not correct you'll have to guess again ^-^")
num =int(input("number:"))
#looping
while num != -abs(1):
wrong.append(num)
print("Nope, guess again:")
if num == -abs(1):
break
av = sum(wrong) / len(wrong)
print ("You got it! The average of your wrong answers is: ")
print(av)
print("The End")
print("Nope, guess again:")
You need to include the input function in the loop if you want it to work. I corrected the rest of your code as well, you don't need the if condition. More generally you should avoid to use break, it often means you are doing something wrong with your loop condition. Here it is redondant and the code after break is never executed.
wrong = []
input("Hi, We're gonna play a guessing game. When asked enter a number between -10 and 10.\nIf not correct you'll have to guess again ^-^")
num = int(input("Number: "))
while num != -1 :
wrong.append(num)
num = int(input("Nope, guess again: "))
av = sum(wrong) / len(wrong)
print(f"You got it! The average of your wrong answers is: {av}\nThe End")
You are just breaking the loop before printing the results, first print the results, then break the loop.
And a while loop isn't necessary for your program, use if condition wrapped in a function instead:
#creating a list for later calculations:
wrong = []
#asking for input:
input("Hi, We're gonna play a guessing game. When asked enter a number between -10 and 10.\nIf not correct you'll have to guess again ^-^")
#looping
def go():
num =int(input("number:"))
if num != -abs(1):
wrong.append(num)
print("Nope, guess again:")
if num == -abs(1):
av = sum(wrong) / len(wrong)
print ("You got it! The average of your wrong answers is: ")
print(av)
print("The End")
break
print("Nope, guess again:")
go()
There are lots of issues in the code.
If you want to get inputs in while looping, you should include getting input code inside the while loop like below,
while num != -1:
......
num =int(input("number:"))
......
Also you don't have to include 'break' inside the while loop because, when num != 1, the loop will stop.
You should ask for input inside your loop, but you just print "Nope, guess again:".
wrong = []
print("Hi, We're gonna play a guessing game. When asked enter a number between -10 and 10.\n"
"If not correct you'll have to guess again ^-^")
num = int(input("number: "))
# looping
while num != -1:
wrong.append(num)
num = int(input("Nope, guess again: "))
av = sum(wrong) / len(wrong)
print(f"You got it! The average of your wrong answers is: {av}\nThe End")
This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 1 year ago.
import random
from random import randint
number = randint(1, 500)
guess = input("The computer has chosen a random number. Guess the number: ")
guess = int(guess)
while guess == number:
print("Congrats, you have won")
break
if guess > number:
print("Lower")
if guess < number:
print("Higher")
This code only allows the user to input one guess and then the program ends. Can someone help me fix this
You should think about your loop condition.
When do you want to repeat? This is the loop condition
When the guess is not correct. guess != number
What do you want to repeat? Put these inside the loop
Asking for a guess guess = int(input("Your guess: "))
Printing if it's higher or lower if guess > or < number: ...
What don't you want to repeat?
You need this before the loop
Deciding the correct number.
Setting the initial guess so the loop is entered once
You need this after the loop
Printing the "correct!" message, because you only exit the loop once the guess is correct
So we have:
number = random.randint(1, 100)
guess = 0
while guess != number:
guess = int(input("Your guess: "))
if guess > number:
print("Lower")
elif guess < number:
print("Higher")
print("Correct!")
Right now, your while loop is useless as once you are in it you break immediately. The rest of the code is not in a loop.
You should rather have an infinite loop with all your code, and break when there is a match:
from random import randint
number = randint(1, 500)
while True: # infinite loop
guess = input("The computer has chosen a random number. Guess the number: ")
guess = int(guess) # warning, this will raise an error if
# the user inputs something else that digits
if guess == number: # condition is met, we're done
print("Congrats, you have won")
break
elif guess > number: # test if number is lower
print("Lower")
else: # no need to test again, is is necessarily higher
print("Higher")
You must take input in the loop, because the value for each step has to be updated .
from random import randint
number = randint(1, 500)
while True:
guess = input("The computer has chosen a random number. Guess the number: ")
guess = int(guess)
if guess == number:
print("Congrats, you have won")
break
if guess > number:
print("Lower")
if guess < number:
print("Higher")
I am learning python, and one of the exercises is to make a simple multiplication game, that carries on every time you answer correctly. Although I have made the game work, I would like to be able to count the number of tries so that when I've answered correctly a few times the loop/function should end. My problem is that at the end of the code, the function is called again, the number of tries goes back to what I originally set it, obviously. How could I go about this, so that I can count each loop, and end at a specified number of tries?:
def multiplication_game():
num1 = random.randrange(1,12)
num2 = random.randrange(1,12)
answer = num1 * num2
print('how much is %d times %d?' %(num1,num2))
attempt = int(input(": "))
while attempt != answer:
print("not correct")
attempt = int(input("try again: "))
if attempt == answer:
print("Correct!")
multiplication_game()
You could surround your call of multiplication_game() at the end with a loop. For example:
for i in range(5):
multiplication_game()
would allow you to play the game 5 times before the program ends. If you want to actually count which round you're on, you could create a variable to keep track, and increment that variable each time the game ends (you would put this inside the function definition).
I would use a for loop and break out of it:
attempt = int(input(": "))
for count in range(3):
if attempt == answer:
print("correct")
break
print("not correct")
attempt = int(input("try again: "))
else:
print("you did not guess the number")
Here's some documentation on else clauses for for loops if you want more details on how it works.
NB_MAX = 10 #Your max try
def multiplication_game():
num1 = random.randrange(1,12)
num2 = random.randrange(1,12)
answer = num1 * num2
i = 0
while i < NB_MAX:
print('how much is %d times %d?' %(num1,num2))
attempt = int(input(": "))
while attempt != answer:
print("not correct")
attempt = int(input("try again: "))
if attempt == answer:
print("Correct!")
i += 1
multiplication_game()
Code:
loop = 0
def main():
while loop == 0:
Num = input("Please Enter The Number Of People That Need The Cocktails ")
print()
print(" Type END if you want to end the program ")
print()
for count in range (Num):
with open("Cocktails.txt",mode="w",encoding="utf-8") as myFile:
print()
User = input("Please Enter What Cocktails You Would Like ")
if User == "END":
print(Num, "Has Been Written To The File ")
exit()
else:
myFile.write(User+"/n")
myFile.write(Num+"/n")
print()
print(User, "Has Been Written To The File ")
Error:
line 9, in main for count in range (Num): TypeError: 'str' object
cannot be interpreted as an integer
I'm trying to set the variable as the number of times it will repeat how many cocktails they would like.
Example:
How many cocktails ? 6
The script should then ask the user to enter what cocktails he wants six times.
In Python, input() returns a string by default. Change Num to:
Num = int(input("Please Enter The Number Of People That Need The Cocktails "))
Also
MyFile.write(Num + "\n")
should read:
MyFile.write(str(Num) + "\n")
And just for the record, you can replace:
loop = 0
while (loop == 0):
with:
while True:
Cast int() on your input to make Num a workable integer. This has to be done because in Python 3, input always returns a string:
Num = int(input("Please Enter The Number Of People That Need The Cocktails "))
With your code in it's current state, you are trying to construct a range from a string, which will not work at all as range() requires an integer.
EDIT:
Now you must replace:
myFile.write(Num+"/n")
with:
myFile.write(str(Num)+"/n")
Num is an integer at this point, so you must explicitly make a string to concatenate it with a newline character.