So im new to python and this question should be fairly easy for anybody in here except me obvisouly haha so this is my code
for c in range(0,20):
print("number",c+1)
number = input ("Enter number:\n")
number = int(number)
if (number < 1 or number > 9):
print("try again by inputing a positive number < 10")
c -=1
so as you may think if the number someone inputs is bigger than 9 or smaller than 0 i just want my c to stay where it is so i get 20 positive numbers from 1-9 instead it doesnt do that and it keeps increasing even tho i have the c-=1 thingy down there
First, do not use range(0,20) but range(20) instead.
Second, range returns an iterator. This means, that when you do c-=1 you do not go back in the iterator, you decrease the number returned by the iterator. Meaning that if c=5 and the number you entered in input is 20, c will become 4, but when returning to the start of the loop, c be be 6.
You probably want something of this sort:
c = 0
while c < 20:
print("number",c+1)
number = input ("Enter number:\n")
number = int(number)
if (number < 1 or number > 9):
print("try again by inputing a positive number < 10")
continue
c += 1
an alternative and simple solution to this would be:
i=20
while(i!=0):
number = input("Enter number:\n")
number = int(number)
if (number <1 or number >9):
print("Invalid no try within 0-9 ")
else
print(number)
i-=1
Related
I know how to do this with a while loop and know how to use a for-loop in other languages like Java and C++. I want to use a for-loop in place of where I have written the while loop asking for the user input.
# You are required to use for-loop to solve this and round your answer to 2 decimal places. Write
# a program that takes n ∈ N (i.e., any positive integer including zero) from the user and use the
# input value to compute the sum of the following series:
n = -1
while n < 0:
n = int(input("Enter a value to compute: "))
# keep asking for user input until a whole number (0, 1, 2, 3, etc...) has been entered
k = 0
sum = 0
# To hold the sum of the fraction to be displayed
lastTerm = 0
# This variable represents the last term to be added to the fraction sum before the while loop below terminates
if n == 0:
sum = 0
elif n == 1:
sum = 1
else:
while lastTerm != 1 / n:
lastTerm = (n - k) / (k + 1)
sum = sum + (n - k) / (k + 1)
k += 1
print("{:.2f}".format(sum))
# Print the sum to two decimal places
One option is to catch the exception which is thrown when you cannot convert the input to an int, i.e.
while(True):
try:
# read input and try and covert to integer
n = int(input("Enter a value to compute: "))
# if we get here we got an int but it may be negative
if n < 0:
raise ValueError
# if we get here we have a non-negative integer so exit loop
break
# catch any error thrown by int()
except ValueError:
print("Entered value was not a postive whole number")
Alternative, slightly cleaner but I'm not 100% sure isdigit() will cover all cases
while(true):
n = input("Enter a value to compute: ")
if value.isdigit():
break
else:
print("Entered value was not a postive whole number")
How about this? It uses the for loop and sums all the values in the list.
x=[1,2,3,4] #== test list to keep the for loop going
sum_list=[]
for i in x:
j=float(input("Enter a number: "))
if not j.is_integer() or j<0:
sum_list.append(j)
x.append(1) #=== Add element in list to keep the cyclone going
else:
break
sums=sum(sum_list)
print("The Sum of all the numbers is: ",round(sums,2))
Use this to check for whole numbers -
if num < 0:
# Not a whole number
elif num >= 0:
# A whole number
for a for loop:
import itertools
for _ in itertools.repeat([]): # An infinite for loop
num = input('Enter number : ')
if num < 0:
# Not a whole number
pass # This will ask again
elif num >= 0:
# A whole number
break # break from for loop to continue the program
Easier Way -
mylist = [1]
for i in mylist : # infinite loop
num = int(input('Enter number : '))
if num < 0:
mylist.append(1)
pass # This will ask again
elif num >= 0:
# A whole number
break
I'm trying to solve this problem but I'm just stuck at the very end.
I need to make a function that cycles the 5 digit number around. So for example, the input is 12345 and then it should be 51234, 45123 etc. Then when it cycles it out, until it's at the beginning again which is 12345, it should print out the biggest number of all of the cycled ones.
def number_cycle(number):
if number >= 99999 or number < 9999:#this is for limiting the number to 5 digits
print('Error,number isnt in 5 digit format')
else:
e = number%10 #5th digit
d = int(((number-e)/10)%10)#4th digit
c = int(((((number - e)/10)-d)/10)%10)#3rd digit
b = int(((((((number - e)/10)-d)/10)-c)/10)%10)#2nd digit
a = int(((((((((number - e)/10)-d)/10)-c)/10)-b)/10)%10)#1st digit
print(e,a,b,c,d)
print(d,e,a,b,c)
print(c,d,e,a,b)
print(b,c,d,e,a)
print(a,b,c,d,e)
number = eval(input('Input number:'))
I can't figure out how to get the biggest number out of all these.
Can you help?
You can try this solution:
def get_largest(number):
num_str = str(number)
num_len = len(num_str)
if num_len != 5:
print(f"Error: {number} is not a 5 digit number")
return
largest = 0
for i in range(num_len):
cycled_number = int(num_str[i:] + num_str[:i])
print(cycled_number)
if cycled_number > largest:
largest = cycled_number
print("Largest: ", largest)
number = int(input("Input number: "))
get_largest(number)
It will basically convert your 5 digit number to a string using a for loop, and then rotate the string, compare the rotated numbers and print the largest one.
Note:
In your original code snippet I'd suggest not to use the built-in eval method as it can be quite dangerous if you don't know what you are doing so avoid it as much as you can except you really have no other way to deal with a problem. More here:
https://nedbatchelder.com/blog/201206/eval_really_is_dangerous.html
https://medium.com/swlh/hacking-python-applications-5d4cd541b3f1
i have to write a program with a loop that asks the user to enter a series of positive numbers. the user should enter a negative number to signal the end of the series, and after all positive numbers have been entered, the program should display their sum.
i don't know what to do after this, or whether this is even right (probably isn't):
x = input("numbers: ")
lst = []
for i in x:
if i > 0:
i.insert(lst)
if i < 0:
break
you should use input in the loop to enter the intergers.
lst = []
while True:
x = int(input('numbers:'))
if x > 0:
lst.append(x)
if x < 0:
print(sum(lst))
break
def series():
sum1 = 0
while True:
number = int(input("Choose a number, -1 to quit:"))
if number>=0:
sum1+=number
else:
return sum1
series()
while True means that the algorithm has to keep entering the loop until something breaks it or a value is returned which ends the algorithm.
Therefore, while True keep asking for an integer input , if the given integer is positive or equal to zero, add them to a sum1 , else return this accumulated sum1
You can use a while loop and check this condition constantly.
i, total = 0, 0
while i>=0:
total+=i
i = int(input('enter number:'))
print(total)
Also, don't use:
for loop for tasks you don't know exactly how many times it is going to loop
while loop as while True unless absolutely necessary. It's more prone to errors.
variable names that have the same name as some built-in functions or are reserved in some other ways. The most common ones I see are id, sum & list.
do you want that type of code
sum_=0
while True:
x=int(input())
if x<0:
break
sum_+=x
print(sum_)
Output:
2
0
3
4
5
-1
14
if you want a negative number as a break of input loop
convert string to list; input().split()
convert type from string to int or folat; map(int, input().split())
if you want only sum, it is simple to calculate only sum
x = map(int, input("numbers: ").split())
ans = 0
for i in x:
if i >= 0:
ans += i
if i < 0:
break
print(ans)
I'm really new to coding (as in about 3 weeks in), and I'm writing a code where the user is asked to input a number between 0 and 100 and then this number is added to a list. Once the list reaches a length of 10 numbers, it should print the list. I'm using a function to this.
I can get it so it prints a list, but it's only printing the first number that is input. For example if I enter 5, it'll still ask for the other numbers, but it prints the list as [5, 5, 5, 5, 5, 5, 5, 5, 5, 5]. Also if I enter a number outside the range of 0-100 it does ask you to input a different number, but then it stops and prints the list as 'None'.
Below is my code:
def getUser(n):
mylist = []
while 0 < n < 100:
mylist.append(n)
int(input("Please enter a number between 0 and 100: "))
if len(mylist) == 10:
return(mylist)
else:
int(input("This number is not in the range of 0-100, please input a different number: "))
n = int(input("Please enter a number between 0 and 100: "))
print("The numbers you have entered are: ", getUser(n))
I'm guessing its to do with the while/else loop but as I said I'm new to this and it all feels so overwhelming, and trying to google this just seems to bring about super complicated things that I don't understand!! Thanks
First : Why you get [5, 5, 5, 5, 5, 5, 5, 5, 5, 5] :
int(input("Please enter a number between 0 and 100: "))
You should give this to n first :
n=int(input("Please enter a number between 0 and 100: "))
Then, it gets out of the loops because you go in the else, and then you don't go back in the while. Then your function ended, without return, so none
To be honest, I don't understand why your code gets out of the while loop if you give a number out of the range, as the value is not given to n. If someone could explain in comment, that would be great !
I would do it like that :
def getUser():
mylist = []
while len(mylist) < 10:
n = int(input("Please enter a number between 0 and 100: "))
if (0 < n < 100):
mylist.append(n)
else:
print('This is not between 0 and 100 !')
return mylist
print("The numbers you have entered are: ", getUser())
Then you will be asked number from 0 to 100 (excluded) until you get a size of 10.
So here's what you were doing wrong
def getUser(n):
mylist = []
while 0 < n < 100:
mylist.append(n)
n = int(input("Please enter a number between 0 and 100: "))
if len(mylist) == 10:
return(mylist)
else:
int(input("This number is not in the range of 0-100, please input a different number: "))
n = int(input("Please enter a number between 0 and 100: "))
print("The numbers you have entered are: ", getUser(n))
You notice any difference in the edited code?
You were never re-assigning the value of the variable n
So you would just add whatever value you passed to getUser every time (and it would be the same value every time)
Don't be afraid to ask for help if you're stuck!
P.S.
You can also move a line somewhere to somewhere else to make it behave a bit better if you're up to the challenge ;)
def getUser(n):
mylist = []
t = True
while t:
n =int(input("Please enter a number between 0 and 100: "))
if n >0 and n<=100:
mylist.append(n)
if len(mylist) == 10:
return(mylist)
t = False
elif n < 0 or n >100:
print('This number is not in the range of 0-100, please input a different number:')
Ok, you are trying to use while instead of if.
Here is what I would do - I will explain it soon:
def get_user():
mylist = []
for i in range(5):
n = int(input("Please enter a number between 0 and 100: "))
if n <= 100 and 0 <= n:
mylist.append(n)
else:
print("This is not between 0 and 100 !")
i = i - 1
return mylist
Going through the code
for i in range(5)
Here we use the for to iterate through a range
of numbers (0 - 5). for will assign i to the smallest
number in the range and constantly add 1 to i every iteration until
i is out of the range. See this for more info on range
if n <= 100 and 0 <= n:
Here and checks if 2 expressions are true.
In this case, if n is less than or equal to hundred and more than or equal to 0.
You could use and any number of times you want like this:
if 1 < 100 and 100 > 200 and 20 < 40:
print("foo!")
Now look at the else :
else:
i = i - 1
Here, we subtract 1 from i and thus, decreasing our progress by one.
Also note that my function is called get_user() and not getUser().
In python, we use snake case and not camel case.
I hope this answer helps. I have given small hints in my answer.
You should google them! I also am not directly giving you the logic.
Try to figure it out! That way you would have a good understanding of what I did.
First, I just want to say I recently started with programming, so I'm not very good. This is my problem:
x = int(input("Write a number between 1-100: "))
while x > 100:
x = int(input("The number must be less than 101: "))
while x < 1:
x = int(input("The number must be higher than 0: "))
else:
print ("The number is:",x)
There's a way to cheat the code by doing this:
Write a number between 1-100: 101
The number must be less than 101: 0
The number must be higher than 0: 101
The number is: 101
I basically don't want the user to be able to write a number higher than 100 or lower than 1.
I'm sorry for the bad explanation but I tried my best and, one again, i recently started programming.
I would just do it like this:
x = int(input("Enter a number in the range [1, 100]: "))
while not (1 <= x <= 100):
x = int(input("That number isn't in the range [1, 100]!: "))
else:
print ("The number is:",x)
You can of course, use nested if statements to make your prompt more informative of the error as follows:
x = int(input("Enter a number in the range [1, 100]: "))
while not (1 <= x <= 100):
if x > 100:
x = int(input("The number must be less than 101: "))
else:
x = int(input("The number must be greater than 0: "))
else:
print ("The number is:",x)
Remember that you can test multiple conditions at once!
Use logical or to test both the condition in a single while:
while not 1 <= x <= 100:
x = int(input("The number must be in range [1, 100]: "))
This will iterate the while loop till the user enters the input less than 1 or greater than 100. You can also notice that, this will lead you to an infinite loop, if user keeps on entering invalid input. I'll let you figure out how to solve this issue.
In Python, unlike other programming languages, expressions like a < b < c have the interpretation that is conventional in mathematics. This means that you can write your while-loop just like this:
x = int(input("Write a number between 1-100: "))
while not 1 <= x <= 100:
x = int(input("The number must be in the range 1-100: "))
else:
print ("The number is:", x)