I'm trying to teach myself python right now, and I'm using exercises from "Learn Python The Hard Way" to do so.
Right now, I'm working on an exercise involving while loops, where I take a working while loop from a script, convert it to a function, and then call the function in another script. The only purpose of the final program is to add items to a list and then print the list as it goes.
My issue is that once I call the function, the embedded loop decides to continue infinitely.
I've analyzed my code (see below) a number of times, and can't find anything overtly wrong.
def append_numbers(counter):
i = 0
numbers = []
while i < counter:
print "At the top i is %d" % i
numbers.append(i)
i += 1
print "Numbers now: ", numbers
print "At the bottom i is %d" % i
count = raw_input("Enter number of cycles: ")
print count
raw_input()
append_numbers(count)
I believe you want this.
count = int(raw_input("Enter number of cycles: "))
Without converting the input to integer, you end up with a string in the count variable, i.e. if you enter 1 when the program asks for input, what goes into count is '1'.
A comparison between string and integer turns out to be False. So the condition in while i < counter: is always False because i is an integer while counter is a string in your program.
In your program, you could have debugged this yourself if you had used print repr(count) instead to check what the value in count variable is. For your program, it would show '1' when you enter 1. With the fix I have suggested, it would show just 1.
convert the input string to integer... count=int(count)
Above has been cleared why the while looped for ever. It loops for a lot(=ASCII code which is really big)
But to fix the while you can simply:
while i<int(counter):
print "At the top i is %d" % i
numbers.append(i)
raw_input returns a string, but i is an integer. Try using input instead of raw_input.
Related
So i'm currently on a course, and one of the objectives for today is to recreate the fizzbuzz game, using a for loop and ranges. I think I pretty much have the objective down but am getting a type error and am too stubborn to look up a solution.
This is my current code:
total = 0
for number in range(1, 101):
if total % 3 == 0:
total = 'Fizz'
elif total % 5 == 0:
total = 'Buzz'
elif total % 3 and 5 == 0:
total = 'Fizz Buzz'
print(number)
This is the error I am receiving:
line 3, in <module>
if total % 3 == 0:
TypeError: not all arguments converted during string formatting
Anyone able to point me in the right direction as to what I am doing wrong? I'm stumped and have tried adding str() to certain parts to see if that fixes the issue.
Currently using python 3.9.1 and am using vs-code to code in.
Edit: thanks for all the helpful prods and suggestions, figured it out :)
Expanding on the comment from #rdas:
In the first execution of the loop:
total = 0
so in the first if statement the condition is true (0%3 ==0)
which sets total to 'Fizz' on line 4.
In the second execution of the loop:
total = 'Fizz'.
So as suggested, total is a string at this point and for strings the % is used for string formatting.
Since 3 is not a valid set of arguments for total as a format string you get the error that you're seeing.
That being said, this probably means that there's a problem with how total is being used in your code!
Its because you are setting total to a string, then using a % operator on that.
For integers, % means mod, for strings it is part of the formatting for printing them.
If you print out the value of number in your loop you can see it gets round the loop the first time, then breaks when total has been changed to a string.
Hi so the question I completed involves while loops and although I finished it and got the expected outcome, I added a random line of code for "fun" to see what it would do, you could call it guessing and checking.
x = int(input())
increase = 0
while x != 0:
increase += x
**x = int(input())**
print(increase)
the line that I guessed has asterisks beside it, can someone please let me know what this simple line does.
If it helps:
My question is to input as many numbers as I please, but when I input the value 0, my code should return the sum of the number I inputted before the zero
x = int(input()) #takes user input string and try to convert to integer data type
increase = 0 # set value to variable increase
while x != 0: # condition
increase += x # it add/sum the value of the variable x to the value of the variable increase
x = int(input()) #takes user input string and try to convert to integer data type inside the while loop
print(increase) # print the value
watch this code in action on pythontutor
The function call input() takes user input from the console and makes it available to your code as a string. int(input()) converts the string input from the user, and tries to cast that value to an integer. That integer is then added to running count you have specified as increase.
Just to point out, you will get an error if a user specifies input that cannot be converted to an int, like typing in 'meow'. It will throw a ValueError.
The while loop waits for you to enter a value. This is done with input(). Because you need an integer (input always returns a string) int() is called on the input, which returns an integer (if possible). Everytime an input is made and converted to an integer the while loop starts the next iteration and checks if the previous input was equal to 0. If so, the while loop stops and (in this case) your print statement is executed.
This is exactly what you wanted to do.
I am working in python 3. I am trying to make a program that does something the amount of times a user tells it to. for some reason it is not working. here is my code:
times = input("amount of times: ")
number = 0
while number < int(times):
print ("hello")
number + 1
What is my problem
you are not incrementing number which leads to an infinite loop.
it should be number+=1
while number < int(times):
print ("hello")
number =number+ 1
Try it out
You may want to use a for loop, depending on the program.
Something like this should work for you
times = input("amount of times: ")
for number in range(int(times)):
print("hello")
I'm trying to make a basic dice roller. When i run this program in Codeskulptor, it throws an error on the randint function. Can I not set the range for it using raw_input plugged into variables? Is there a different function I should use?
"""Program to roll random numbers within the ranges set."""
import random
sides_of_die=raw_input("Enter how many sides your die has: ")
number_of_dice=raw_input("Enter number of dice you have: ")
total=sides_of_die*number_of_dice
rollinput=raw_input("Would you like to roll now?")
rollinputcap=rollinput.upper()
if rollinputcap =="Y":
print random.randint(number_of_dice,total)
else:
print "What do you want then?"
raw_input() returns a string, not an integer. To convert it to an integer type, use int():
sides_of_die = int(raw_input("Enter how many sides your die has: "))
number_of_dice = int(raw_input("Enter number of dice you have: "))
What's happening in your code is, you may input "6" and "2", so when you do total = sides_of_die * number_of_dice, you're getting a TypeError
This is just because raw_input returns a string, not a number, while randint accept two numbers as arguments
so you should do
total = int(raw_input(..))
Point is, this is not always secure. Exceptions are very likely to be thrown, so you might want to use a try block; but for the time being, I think it's okay (I'm assuming you're just learning Python).
Another thing, which is rather important:
Look at the exception! If you'd read it, you would have known exactly what the problem was.
Beside the raw_input() problem pointed out by the others, #Mark Ransom's comment is important: the sum of dice value eventually follows normal distribution. See: http://en.wikipedia.org/wiki/Dice#Probability
Your:
if rollinputcap =="Y":
print random.randint(number_of_dice,total)
should be changed to
if rollinputcap =="Y":
sum_dice=[]
for i in range(number_of_dice):
sum_dice.append(random.randint(1, sides_of_dice))
print sum(sum_dice)
Below is a piece of code from Python which has been bothering me for a while.
var=0
while (var <1 or var>100):
var=raw_input('Enter the block number ')
if (var >=1 and var<=100):
print '\nBlock Number : ',var
else:
print 'ERROR!!! Enter again.'
The problem is that the while loop iterates continuously without breaking. Can anyone help me how to break the loop.
Is there any way to implement a do..while in Python?
The problem is that raw_input returns a string. You're comparing a string with an integer which you can do in python 2.x (In python 3, this sort of comparison raises a TypeError), but the result is apparently always False. To make this work you probably want something like var=int(raw_input('Enter the block number'))
From the documentation:
objects of different types always compare unequal, and are ordered consistently but arbitrarily.
You're needlessly checking var twice, and you're trying to compare int and str (because raw_input returns a string), which doesn't work right. Try this:
var=0
while True:
var=int(raw_input('Enter the block number '))
if (var >=1 and var<=100):
print '\nBlock Number : ',var
break
else:
print 'ERROR!!! Enter again.'
You should convert your string to int.
var=0
while (var <1 or var>100):
# I changed here
var=int(raw_input('Enter the block number '))
if (var >=1 and var<=100):
print '\nBlock Number : ',var
else:
print 'ERROR!!! Enter again.'
You're running into an issue that strings (as returned by raw_input) are always greater than integers:
>>> "25" > 100
True
You need to convert your input to an integer first:
var = int(raw_input("Enter the block number "))
Of course, you'll want to be resilient in the face of bad input, so you'll probably want to wrap the whole thing in a try block.
hello you need to enter "break" and also var should be an integer, see below
while True:
var=int(raw_input('Enter the block number '))
if (var >=1 and var<=100):
print '\nBlock Number : ',var
break
else:
print 'ERROR!!! Enter again.'
continue
hope this helps