This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed 4 years ago.
I want this python code comes out from loop when I enter 0 as input number of "num" variable But it continues printing these three lines constantly
Thanks
num = 10 #10 is dummy number for starting loop
while(num!=0):
print("1)Test func1")
print("2)Test func2")
print("0)Exit")
num = input("Enter a number:")
print("Comes out from while loop!")
There reason behind is that the input takes input as a string and you have to either convert it to int:
num = int(input("Enter a number:"))
or change the while loop:
while(num!='0'):
print takes input as string , in order to come out of loop
use
num = int(input("Enter a number:"))
it will consider num variable as an integer but not an string and will come out of the loop.
You have got a correct answer before this but you can change your code too:
while True:
print("1)Test func1")
print("2)Test func2")
print("0)Exit")
num = input("Enter a number:")
if num == '0':
break
print("Comes out from while loop!")
at the begining while always get True, you don't need to set value, 'break' means 'stop current loop and exit'
Related
This question already has answers here:
Check if a number is odd or even in Python [duplicate]
(6 answers)
Closed 1 year ago.
I would just like a tip on how to send even numbers to the left and odd numbers to the right, I've been trying for a long time and I can't, the subject is composed lists, I appreciate any help. Simplified code below without loop or conditional structure.
test = [[],[]]
num = int (input("Type it : "))
test.append()
print(test)
test = [[], []]
num = input("Enter a number or quit")
while num != "quit": # execute code as long as num is not quit
num = int(num) # convert num to a number (until here, it's a string !!!)
if num % 2 == 0: # num is even
test[0].append(num)
else: # num is odd
test[1].append(num)
print(test)
This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed 3 years ago.
I'm new to Yython programming. I create a simple program with random module, that ask for number, and person need to guess an number. I got problem with getting the answer. Even if I give the correct answer, program isn't stopping, here's the code:
import random
run = True
answer = random.randint(1,9)
guess = input("Give me an number in 1 to 9: ")
print(answer)
while run:
if guess == answer:
print("Congratulations, you won!\n" * 5)
run = False
else:
guess = input("Try again: ")
print(answer)
The print(answer) line is for me to know what is the answer, and even if I write it down, program isn't stopping.
answer is always an integer:
answer = random.randint(1,9)
and guess is always a string:
guess = input("Give me an number in 1 to 9: ")
thus they can never be equal.
You need to conver the inputted string to an integer:
guess = int(input("Give me an number in 1 to 9: "))
Or better yet, convert the generated random number to a string, to avoid the issue of the program crashing when the user inputs a non digit:
answer = str(random.randint(1,9))
The random function will return an integer and the input function will return a string in python, "1" is not equal to 1. To be able to check if the input is the same, convert the random number to a string by doing guess == str(answer) instead
This question already has answers here:
How do I add five numbers from user input in Python?
(5 answers)
Closed 6 years ago.
I'm trying to help my son who's got some Python homework from school...and I haven't coded since school and this is my first evening on python so forgive the dumb question.
Using a "For" statement I need to prompt the user to enter 10 numbers. When the entries have ended, I need to display the sum. I know I need to do something linking newsum/oldsum/+ value entered but I'm stuck. All help gratefully received.
Here's where I've got to:
total=int
runningtotal=int
thisinput=int
n=0
for num in range (1,11):
runningtotal=thisinput+n
print("enter number",num)
n=int(input())
thisinput=n
print(runningtotal)
The answer is:
inputs_sum = 0
for x in range(10):
inputs_sum += int(input('Enter number:'))
print('The sum is {}'.format(inputs_sum))
Enjoy!
In python3.x, using your code as a working model, probably something like this:
runningtotal=0
for num in range(10):
thisinput = input("enter number: ") # If using python2.x change input to raw_input
runningtotal+=int(thisinput)
print(runningtotal)
Another answer (was deleted) used list.append() to add numbers to list and sum the list elements like so:
num_list = []
for num in range(10):
thisinput = raw_input("enter number: ")
num_list.append(int(thisinput))
print sum(num_list)
This question already has answers here:
Python: raw_input and unsupported operand type(s)
(3 answers)
Closed 7 years ago.
I am trying to ask the user to enter any number and then ask the user to enter any names, then store this input in a list.
However, when I enter any number, it asks to enter name only one time and shows the output in list:
def main():
# a = 4
a = input("Enter number of players: ")
tmplist = []
i = 1
for i in a:
pl = input("Enter name: " )
tmplist.append(pl)
print(tmplist)
if __name__== "__main__":
main()
output:
Enter number of players: 5
Enter name: Tess
['Tess']
The for loop should run 5 times and user entered 5 values get stored in a list.
You need to convert the number of players to integer and then loop for that much amount of times, you can use the range() function for this . Example -
def main():
num=int(input("Enter number of players: "))
tmplist=[]
for _ in range(num):
pl=input("Enter name: " )
tmplist.append(pl)
print(tmplist)
Since you are using Python3
a=input("Enter number of players: ")
means a is a string "5". Since this is only one character long - the loop will run just once
You need to use
a = int(input("Enter number of players: "))
You'll also need to change the loop
for i in range(a):
I recommend using more meaningful variable names - especially if this is homework
def main():
number_of_players = int(input("Enter number of players: "))
player_list = []
for i in range(number_of_players):
player = input("Enter name: " )
player_list.append(player)
print(player_listlist)
if __name__== "__main__":
main()
You got a string a which presumably contained something like '5'. Then you initialize a counter i. Then you loop through this string, which, since it's '5', resulted in one iteration, because there's only one character in '5'.
First you have to change it into a number, with a = int(a).
With a as a number, you still can't loop through that, because a number isn't an iterable.
So then you should create a range object to loop over, with for i in range(a):.
Then you will be able to carry out your operations as expected.
Since the input a is a string
you need to convert it to a number and then use a different for.
it should be
def main():
#a=4
a=int(input("Enter number of players: "))
tmplist=[]
i=0
while i < a:
pl=input("Enter name: ")
tmplist.append(pl)
i+=1
print(tmplist)
main()
This question already has answers here:
Is it possible to implement a Python for range loop without an iterator variable?
(15 answers)
Closed 3 months ago.
So I have this assignment and I have a question about a part I don't know how to do, can you guys help me?
def main():
# Please see the comments
largest = 0
for index in range(3): # Enter the value(s) in the parenthesis to run the loop 3 times
number1 = int(input("Please enter the first number: "))
number2 = int(input("Please enter the second number: "))
number3 = int(input("Please enter the third number: "))
# insert call to function find_largest after this comment.
# find_largest will take in three parameters and will return the largest of the 3 numbers
result = find_largest(number1, number2, number3)
# insert the statement to print the three numbers entered and the largest number after this comment.
print("The numbers you entered were, \n", [number1, number2, number3])
print ("The largest of the numbers you entered is", result)
def find_largest(a, b, c):
# insert parameters in the parenthesis
# Write the code for this function here.
# find_largest will take in three parameters and will return the largest of the 3 numbers
# These three numbers are passed in as parameters from the main function
# Hint: if and elif - no loop needed here
if (a > b) and (a > c):
largest = a
elif (b > a) and (b > c):
largest = b
else:
largest = c
return largest
main() # this is the call to main() that will make the program run
So, my question is the part:
for index in range(3): # Enter the value(s) in the parenthesis to run the loop 3 times
I don't know what to add so the loop run 2 more times after it has found the largest number
The loop you have makes the first two iterations of the loop pointless, as each time you loop, you are reassigning new numbers to the three number variables. As a result, only the numbers entered in the last iteration of the loop are ever used for anything. I think this would make more sense:
numbers = []
for i in range(3):
input = int(input("Enter number: "))
numbers.append(input)
This will give you a list called numbers with 3 numbers in it entered by the user. Then you can do what you want with them. Having said that, you really don't need a for loop to do this. As Craig Burgler mentioned.
Alternatively(though this doesn't use range...):
number1 = 0
number2 = 0
number3 = 0
for i in (number1, number2, number3):
i = int(input("Enter number: "))
The code as written will ask for three numbers three times, overwriting the first and second set of numbers that the user enters. If the assignment is to get three numbers from the user and tell the user which is largest, then you do not need the for loop. The three input statements will do the trick.