I want to input a series of numbers and end with "stop", the while loop is to check if x is not equal to the 'stop', it continues add up the input number and output the sum for each loop, however the while loop falls into infinity. For example, my input is:
12
35
56
23
56
455
556
344
22
22
stop
#read the input
x = input()
#add up by a loop
T = 0
x_int = int(x)
while x != 'stop':
for i in range(1, 10):
T += x_int
print(i, T)
You need to prompt for the next input in the while loop. As stands, you never prompt for additional data and so you will never see the stop. I added a prompt so that it is more clear.
#add up by a loop
T = 0
while True:
x = input("enter data: ")
if x == 'stop':
break
x_int = int(x)
for i in range(1, 10):
T += x_int
print(i, T)
Several of us are confused about how you want to enter data. If you don't want any prompts and want to read any number of lines from the user (or perhaps piped from another program) you could read stdin directly.
#add up by a loop
import sys
T = 0
for line in sys.stdin:
x = line.strip()
if x == 'stop':
break
x_int = int(x)
T += x_int
print(i, T)
Try this program and see if it works. The problem with your code was there is no need of a for loop. I didn't understand why it was used there in your program, hope you understood.
T = 0
i = 0
while True:
x = input("enter data: ")
if x == 'stop':
break
else:
i =i+1
x_int = int(x)
T += x_int
print(i, T)
Related
I'm trying to create a function. Function; it will simply be designed to increase the last letter sequence from its position in the alphabet or letter list.
import time
def CountDown(text,reply=3):
abc = list("ABCDEFGHIJ")
c = 1
text_list = list(text)
while 1:
Index = abc.index(text_list[-c])
if not list(filter(lambda a: a!=abc[-1], text_list)):
return "".join(text_list)
if text_list[-c] == abc[-1]:
text_list[-c] = abc[0]
c += 1
continue
else:
s=1
while 1:
text_list[-c] = abc[(Index+s) if (Index+s)<len(abc) else 0]
if text_list.count(abc[(Index+s) if (Index+s)<len(abc) else 0])+1<reply:
break
s+=1
text_list[-c] = abc[(Index+s) if (Index+s)<len(abc) else 0]
return "".join(text_list)
if __name__ == "__main__":
code="ABHD"
while 1:
code=CountDown(code)
time.sleep(0.5)
print(code)
OUTPUT:
ABHE
ABHF
ABHG
ABHI
ABHJ
ABIA
ABIC
ABID
ABIE
ABIF
ABIG
ABIH
ABIJ
ABJA
ABJC
ABJD
ABJE
ABJF
ABJG
ABJH
ABJI
....(idling)
The code doesn't give an output after a while. I think there is something wrong.
How can I fix this code sample?
I am going to write a guessing game with the computer.
I choose one number in my head and the Computer is going to find it out, and it can guess between a range.
The problem is I don’t know how can I update this range during the program run.
import random
x = 1
y = 99
guess= random.randint(x,y)
print(guess)
play='true'
while play=='true':
a=x
b=y
results = input()
if results == 'd':
play='false'
else:
if results == 'b':
a=guess
print('My number is bigger!')
newguess= random.randint(a,b)
print (newguess)
elif results == 'k':
b=guess
print('My number is smaller!')
newguess= random.randint(a,b)
print (newguess)
print ('Wooow , computer you did it! ')
Sorry about all the explanations in the code but this is a version of the game that I did a while ago. What I did was I wanted to shrink the guessing range each time the user said high or low. e.g. if the computer chooses 50, and the user says 'High' then the program will not chose a number greater than 50, the same applies for 'Low". Enjoy
import random
count = 0 #Number of attemps. how many times while loop runs.
guess = random.randint(1,100)#The guess generator
(l,u) = (0,100)
lower_guess = l
upper_guess = u
n = 0
print('Chose a number between ', l, ' and ', u , '.' )
#The game. These are outside the function so that they don't print in every loop because they are unwanted for some Y inputs.
print('Is it ' + str(guess))
Y = input('Low = L, High = H and Yes = Y:')#User states
#The function
while n != 'guess':
count +=1 #adds 1 to count each time loop runs
if Y == 'L':
lower_guess = guess+1
guess = random.randint(lower_guess , upper_guess)#Redifining guess to eliminate irrelevant guesses from the range
print('Is it ' + str(guess))
Y = input('Low = L, High = H and Yes = Y:')
elif Y == 'H':
upper_guess = guess - 1
guess = random.randint(lower_guess, upper_guess)#Redifining guess to eliminate irrelevant guesses from the range
print('Is it ' + str(guess))
Y = input('Low = L, High = H and Yes = Y:')
elif Y == 'Y':
print('I guessed it in ' + str(count) + ' attempts')
break
else:
count = 0
lower_guess = l
upper_guess = u
guess = random.randint(1,100)
print('That input was invalid. The game has restarted.')
print('You can chose a new number or keep your old one.')
print('Is it ' + str(guess))
Y = input('Low = L, High = H and Yes = Y:')
I want to make this code keep going? I tried put an x == to str, but I think that could not be the answer.
while True:
x = int(input("Please enter an integer:
"))
if x < 0:
x = 0
print('Negative changed to zero')
elif x == 0:
print('Zero')
elif x == 1:
print('Single')
else:
x == str :
input("please enter a string")
The first line of your loop can have one of two effects: either x is guaranteed to be an int, or you'll raise a ValueError. Catch the error and restart the loop, or continue with the body knowing that x is an int
while True:
x_str = input("Please enter an integer: ")
try:
x = int(x)
except ValueError:
print("{} is not an integer; please try again".format(x))
continue
if x < 0:
x = 0
print('Negative changed to zero')
elif x == 0:
print('Zero')
elif x == 1:
print('Single')
I'll try to guess what you wanted. I think you wanted a function that is like input, but with a strange twist: if what is entered (x) can be interpreted as an integer, then it returns the integer itself, not x. For example, if the user enters -72, it returns -72, not '-72'. Of course, if the user enters something that cannot be interpreted as an integer, the function returns it without modification.
Of course, being strongly typed, Python doesn't provide such a function, but it's easy to write one. And you don't even need try if you just intend to accept "ordinary"-looking integers.
def intput(prompt=''):
entered = input(prompt)
if entered[entered.startswith('-'):].isdigit(): return int(entered)
else: return entered
while True:
x = intput('Please enter an integer: ')
if x < 0:
x = 0
print('Negative input changed to zero')
elif x == 0: print('Zero')
elif x == 1: print('Single')
elif isinstance(x, str): print('You have entered a string that cannot be '
'easily interpreted as an integer.')
I have some problems with this small program for rolling two dices.
Why the program stops before it finishes the loop and instead it asks a loop times "do you want to play again?"
Thank you for your help!
#Program which simulates the rolling of two dice
import random
def rolling_dices(repetitions):
a = repetitions
b = 1
while b <= a:
i = (random.randrange(1,7))
y = (random.randrange(1,7))
b +=1
print(i, y, "\t =>", int(i+y))
answer = input("do you want to play again? (Y/N)")
if answer.lower() == "y":
continue
else:
break
rolling_dices(5)
Seems like you want to remove the question from the dice-rolling loop and instead put the dice-rolling loop into a loop with the question prompt.
import random
def rolling_dices(repetitions):
a = repetitions
b = 1
while b <= a:
i = (random.randrange(1,7))
y = (random.randrange(1,7))
b +=1
print(i, y, "\t =>", int(i+y))
rolling_dices(5)
while input("do you want to play again? (Y/N)").lower() == "y":
rolling_dices(5)
print("done.")
Make sure to correctly indent the while loop:
#Program which simulates the rolling of two dice
import random
def rolling_dices(repetitions):
a = repetitions
b = 1
while b <= a:
i = (random.randrange(1,7))
y = (random.randrange(1,7))
b +=1
print(i, y, "\t =>", int(i+y))
answer = input("do you want to play again? (Y/N)")
if answer.lower() == "y":
continue
else:
break
rolling_dices(5)
More info on indentation in python: http://www.diveintopython.net/getting_to_know_python/indenting_code.html
l = []
print("We will need some information first.")
t_first_name = input("User First Name: ").lower()
while len(t_first_name) == 0 or t_first_name == ' ':
t_first_name = input("User First Name: ").lower()
while len(t_last_name) == 0 or t_last_name == ' ':
t_last_name = input("User Surname: ").lower()
f_n_up = t_first_name.upper()
l_n_up = t_last_name.upper()
f_n_title = t_first_name.title()
l_n_title = t_last_name.title()
l.append(t_first_name) # Lowercase
l.append(t_last_name)
l.append(f_n_up) # Uppercase
l.append(l_n_up)
l.append(f_n_title) # The first letter is uppercase
l.append(l_n_title)
f = open("p_list.txt", "a")
for x in l:
print(x)
if len(x) >= 5:
f.write(x)
print("test")
It will show the print lines and it create the file, but when i open it, i don't find any words in it.
It will ask for the user name and then make a list about him, adding it to a list l and then make a loop inside it and write the string in the file.
You should either call f.close() or f.flush() for the data to be actually written to the file.
Another (and better) solution is to use with to handle the file opening and closing for you:
with open('p_list.txt', 'a') as f:
for x in l:
print(x)
if len(x) >= 5:
f.write(x)
print("test")