Why is this while statement looping infinitely? - python

I am using Python 2.7 in Windows PowerShell.
def loop(loop):
i = 0
numbers = []
while i < loop:
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
value = raw_input("Choose the loop value:\n>")
print value
loop(value)
When I enter 6 as the input for value, loop() turns into an infinite loop.
Any idea what is going wrong?

The result of your raw_input, the variable value (passed to loop in your function) is a string. You are comparing this to i, an integer. In Python 2.x, all integers are less than all strings, so i < loop is always true no matter how big i gets.
Convert your input to an integer to make the comparison work:
value = int(raw_input("Choose the loop value:\n>"))
(And I'd also suggest not naming your function's argument the same as the function itself; it's just confusing.)

You have to put your raw_input in int().
replace:
value = raw_input("Choose the loop value:\n>")
on:
value = int(raw_input("Choose the loop value:\n>"))
OR you can just change:
while i < loop:
to
while i < int(loop):

I am sure you are actually running loop('6') rather than loop(6).

because value is a string
you should call your function like this
loop(int(value))

Related

I need assistance for my little program (python lists)

I will give you my python code (it's pretty basic and small) and if you can,tell me where i am wrong.I am noob at coding so your help will be valuable.thanks a lot and don't hate :)
lista=[]
for i in range(100):
a=input("give me a number")
if a%2==0:
a=0
else:
a=1
lista=lista+a
print lista
P.S: I code with python 2 because my school books are written with that in mind.
You need to use append method to add an item to the end of the list.
lista.append(a)
And you need to convert the str returned by input() to int.
The input() function reads a line from input, converts it to a string (stripping a trailing newline), and returns that. When EOF is read, EOFError is raised.
a = int(input("give me a number"))
Try this:
lista=[]
for i in range(2): # Changed from 100 to 2 for my own testing
a = int(input("Give me a number: "))
a = 1 if a%2 else 0
lista.append(a)
print(lista)
Outputs:
[0,1]
EDITED:
So i cant use Lista=lista +a?I thought i could..my book says i can..thanks for your solution,it works!
You can use += operator (similar to extend()) but it requires a list operand. Not an int. So, you need to convert your int to a list. Try this:
lista += [a]
list.append(a) is faster, because it doesn't create a temporary list object. So, better to use append.

Issues with multiplication table output

I'm trying to print out the multiplication table and my function prints out one row at a time.
It works fine alone, but when I run multitable(n) through a for loop, it prints out "None" at the end of each row.
Why is this happening and how do I get rid of it?
def multitable(n):
for num in range (1,12+1):
print(num*n,end = " ")
#multitable(1)
#multitable(2)
for n in range (1,12+1):
print(multitable(n))
Replace this:
print(multitable(n))
with this:
multitable(n)
Your program is printing None because that's the value that multitable() is returning. If you don't want to see it, all you have to do is to avoid printing it.
mutlitable(n) does not return anything and thus returns None, which you then print. Seperate the statements.
def multitable(n):
for num in range (1,12+1):
print(num*n,end = " ")
#multitable(1)
#multitable(2)
for n in range (1,12+1):
multitable(n)
print()
It's the return value of the function, which you print out. If there is no return statement
https://docs.python.org/3/reference/simple_stmts.html#return
Like the accepted answer multitable(n) will do the needful, otherwise return the function
for n in range (1,4):
multitable(n)
print()

Change range start in Python 'for loop' for each iteration

I'm a novice and learning python (using 2.7). I'm attempting some simple scripts to test how python handles different types of loops.
My question is: can python change the starting point of the "range" function on each iteration if the start point is assigned to a variable? Here is an example of my code:
def build(n, period):
n2 = n
for digit in range(int(n2), 20):
print "At the top i is %d" % n
digit += period
numbers.append(digit)
print "Numbers now:", numbers
print "At the bottom i is %d" % digit
print "The Numbers:"
n2 += period
for num in numbers:
print num
key = raw_input("Press 1 to call function \"build\", press any other key to quit.")
if key == "1":
i = raw_input("What integer is our start value?")
amt = raw_input("What is the common difference?")
numbers = [int(i)]
build(int(i),int(amt))
else:
quit()
I tried to use a second local variable 'n2' inside the function so I could keep the initial value of 'n' constant and then redefine the range for each iteration. The very first number in the appended list moves by the common difference but after that it always steps by +1 integer. I can easily make this happen with a 'while' loop but curious if a 'for' loop can be used to accomplish this?
range creates a fixed list the moment you call that function at the beginning of your for loop. You can think of the top of the for loop as assigning n2 to the next element of that list no matter what you do inside the loop. If you want to change the period of the range, use the third argument:
range(n, 20, period)
will move in steps of size period through the range instead of steps of size one.
It won't work in a way you expect. Expression range(int(n2), 20) gets evaluated only one time in the beginning of for-loop. You can't change the scope of a for-loop that way.
What you can modify is a step parameter in range function, but it does not change your starting point - it only defines what is the next element in the iteration process.

Text Based RPG Functioning Error?

So, I'm hard at work on a text-based RPG game on Python 2.7, but I came across a problem in the character menu. Here's what it looks like:
def raceselect(n):
if n==0:
print "(name) the Human."
if n==1:
print "(name) the Dwarf."
if n==2:
print "(name) the Elf."
if n==3:
print "(name) the Halfling."
n = raw_input
raceselect(n)
0, 1, 2, and 3 are all used as raw_input answers on the previous screen when prompted with the options. However, when the script is run, the options are shown, and the input box shows, however when a number is answered the script simply ends. I can't for the life of me figure out what is causing this, unless it's the fact that I used (name) and raw_input earlier in the script, which I doubt. Please help!
--Crux_Haloine
You need to turn the raw input into a int:
n = int(raw_input())
Also, you need to call the function, so use raw_input() rather than just raw_input
n = raw_input here will bring nothing to you. You should use n = int(raw_input()) according to your need. And I think it is better for you to use a dict or list rather than several if:
def raceselect(n):
races = {0: 'Human', 1: 'Dwarf', 2: 'Elf', 3: 'Halfing'}
if n in races:
print '(name) the %s' % races[n]
else:
print 'wrong input'
First issue is this:
n = raw_input
You never actually call the function. Instead, your are assigning a reference of raw_input to n (as in, n is now the function, not the result of the function).
Also, once you call the function, you have to cast it into an integer, because raw_input returns a string.
Thus, you want:
n = int(raw_input()).

Adding slicing numbers using a loop

I want to know how can I add these numbers in Python by using a loop? Thanks
num=input("Enter your number: ")
ansAdd= int(str(num)[7])+int(str(num)[5])+int(str(num)[3])+int(str(num)[1])
print....
you want to do it using a loop, here you go:
ansAdd = 0
for x in [7,5,3,1]:
ansAdd += int(str(num)[x])
However, using list comprehension is more pythonic
>>> s = '01234567'
>>> sum(map(int, s[1::2]))
16
Here is how it works:
s[1::2] takes a slice of the string starting at index 1 to the end of the string stepping by 2. For more information on slices see the Strings section of the Python Tutorial.
map takes a function and an iterable (strings are iterable) and applies the function to each item, returning a list of the results. Here we use map to convert each string-digit to an int.
sum takes an iterable and sums it.
If you want to do this without the sum and map builtins, without slices, and with an explicit for-loop:
>>> s = '01234567'
>>> total = 0
>>> for i in range(1, len(s), 2):
... total += int(s[i])
...
>>> total
16
>>> num=input()
12345678
>>> sum(map(int,num[:8][1::2]))
20
here num[:8][1::2] returns only the numbers required for sum(), num[:8] makes sure only the elemnets up to index 7 are used in calculation and [1::2] returns 1,3,5,7
>>> num[:8][1::2]
>>> '2468'
It seems you want to sum odd-numbered digits from user input. To do it with a loop:
num_str = raw_input("Enter your number: ")
ansAdd = 0
for digit in num_str[1::2]:
ansAdd += int(digit)
(The syntax [1::2] is python's string slicing -- three numbers separated by : that indicates start index, stop index and step. An omitted value tells python to grab as much as it can.)
There's a better way to do this without using a traditional loop:
num_str = raw_input("Enter your number: ")
ansAdd = sum(int(digit) for digit in num_str[1::2])
In python 2, input executes the entered text as python code and returns the result, which is why you had to turn the integer back into a string using str.
It is considered a security risk to use input in python 2, since the user of your script can enter any valid python code, and it will be executed, no questions asked. In python 3 raw_input has been renamed to input, and the old input was removed (use eval(input()) instead).

Categories

Resources