I have this exercise:
Receive 10 integers using input (one at a time).
Tells how many numbers are positive, negative and how many are equal to zero. Print the number of positive numbers on one line, negative numbers on the next, and zeros on the next.
That i need to solve it with control/repetition structures and without lists. And i'm stuck in the first part in dealing with the loops
Until now I only writed the part that deal with the amount of zeros, I'm stuck here:
n = float(input()) #my input
#Amounts of:
pos = 0 # positive numbers
neg = 0 # negative numbers
zero = 0 # zero numbers
while (n<0):
resto = (n % 2)
if (n == 0): #to determine amount of zeros
zz = zero+1
print (zz)
elif (resto == 0): #to determine amout of positive numbers
pp = pos+1
print (pp)
elif (n<0): #to determine amount of negative numbers
nn = neg+1
else:
("finished")
My inputs are very random but there are like negatives and a bunch of zeros too and obviously some positive ones. What specific condition i write inside while to make it work and to make a loop passing by all the numbers inside a range of negative and positive ones?
Soo.. i made it turn into float because theres some broken numbers like 2.5 and the inputs are separated by space, individual inputs of numbers one after other
example input (one individual input at a time):
25
2.1
-19
5
0
# ------------------------------------------
# the correct awnser for the input would be:
3 #(amount of Positive numbers)
1 #(amount of Negatives numbers)
1 #(amount of Zeros numbers)
how to make them all pass by my filters and count each specific type of it?
obs: i can't use lists!
If I understood you right, I think the below code may be what you are after.
Wishing you much success in your future ventures and projects!:D
pos_count = 0
neg_count = 0
zero_count = 0
turn_count = 0
while turn_count < 10:
user_input = input("Please enter a whole number: ") #Get input from user
try:
user_number = int(user_input) # Catch user input error
except:
print("Input not valid. Please enter a whole number using digits 0-9")
continue # Start over
# Check each number:
if user_number > 0:
pos_count += 1
turn_count +=1
elif user_number < 0:
neg_count += 1
turn_count +=1
elif user_number == 0:
zero_count += 1
turn_count +=1
print("Positive count:", pos_count) # Print positive count
print("Negative count:", neg_count) # Print negative count
print("Zero count:", zero_count) # Print zero count
Why not something like this?
pos = 0
neg = 0
zer = 0
for x in range(10):
number = int(input())
if number > 0:
pos +=1
if number < 0:
neg +=1
else: # number is not positive and not negative, hence zero
zer +=1
print(pos)
print(neg)
print(zer)
EDIT: Thanks #Daniel Hao for pointing out that casting to int is necessary with input().
Related
I want to calculate the sum of the natural numbers from 1 up to an input number. I wrote this code:
number=int(input("enter a natural number"))
if number<0:
print("The number is not positive")
else:
n=0
for i in range (1,number+1):
n+=i
print(n)
But it prints multiple numbers instead. For example, if the user puts five, the program should print 15, but I get this:
1
3
6
10
15
How can I fix the code so that only 15 appears?
You have all the steps because your print statement is in your for loop.
Change it like this:
number = int(input("Enter a positive natural number: "))
if number < 0:
print("The number needs to be positive")
exit() # Stops the program
result = 0
for i in range(1, number + 1):
result += i
print(result) # We print after the calculations
There's also a mathematical alternative (see here):
number = int(input("Enter a positive natural number: "))
if number < 0:
print("The number needs to be positive")
exit() # Stops the program
print(number * (number + 1) / 2)
As I've pointed out and suggested earlier in comments, you could move the print statement out of for-loop to print the final sum.
Or you could try to use generator expression to get all number's total (sum), because we don't care the intermediate sums.
This simple sum of all up to the number in one shot.
number=int(input("enter a natural number"))
if number < 0:
print("The number is not positive")
# exit or try again <---------
else:
print(sum(range(1, number + 1))) # given 5 -> print 15
Something like this?
number = int(input("enter a natural number"))
if number < 0:
print("The number is not positive")
else:
n = 0
for i in range (1,number + 1):
n += i
print(n)
The answer to your question is that you are printing the n every time you change it. You are looking for the last answer when you run the code. This code should solve it.
number = int(input("enter a natural number"))
if number < 0:
print("The num < 0")
else:
n = 0
l = []
for i in range (0, number+1):
n+=i
l.append(n)
print(l[len(l)-1])
I am trying a similar thing like this: 4 Digit Guessing Game Python . With little changes.
The program generates random numbers between 999 and 10000.User after every failed attempt gets how many numbers he guess in the right spot and how many numbers he got right but didn't guess position correctly.
Etc. a random number is 3691 and the user guess is 3619. He gets 2 numbers in the correct position (3 and 6) and also 2 numbers correct but in the wrong position (1 and 9).
There is no output when for numbers he didn't guess and guessing is repeating until all 4 digits are guessed in the right spot.
My idea is we save digits of the random number to a list and then do the same thing with user guess number. Then we compare the first item of both lists etc. combination_list[0] == guess_ist[0] and if it's correct we add +1 on counter we call correct.
The problem is I don't have an idea for numbers that are guessed correctly but are not in the correct position.
import random
combination = random.randint(1000, 9999)
print(combination)
digits_combination, digits_guess= [], []
temp = combination
while temp > 0:
digits_combination.append(temp % 10)
temp //= 10
digits_combination.reverse()
print(digits_combination)
guess= int(input("Your numbers are? "))
while not 999 < pokusaj < 10000:
pokusaj = int(input("Your numbers are? "))
if guess!= combination:
while guess> 0:
digits_guess.append(guess% 10)
guess//= 10
digits_guess.reverse()
if guess == combination:
print("Your combination is correct.")
correct_position= 0
correct= 0
test = digits_combination[:] # I copied the list here
while guess!= combination:
while guess> 0:
digits_guess.append(guess% 10)
guess //= 10
digits_guess.reverse()
if digits_guess[0] == test[0]:
correct_position += 1
I have this solution. I suggestion you to cast to string and after cast to list to get a list of number digits instead to use a while loop. For the question you can try to use "in" keywords to check if number in digits_combination but not in right position.
import random
combination = random.randint(1000, 9999)
print(combination)
digits_combination = list(str(combination))
guess= int(input("Your numbers are? "))
while not 999 < guess < 10000:
guess = int(input("Your numbers are? "))
digits_guess = list(str(guess))
if guess == combination:
print("Your combination is correct.")
correct_position = 0
correct = 0
for index, value in enumerate(digits_guess):
if value == digits_combination[index]:
correct_position += 1
elif value in digits_combination:
correct += 1
I have been given the following Pseudocode snippet
Function number_function()
Initialise variables factorial, number
Initialise Boolean valid to false
Loop while not valid
Display “Please enter a positive integer greater than 0”
Input number
If number contains numeric characters
Convert number to integer
If number is a positive integer
Set valid to true
End if
End if
End loop
Loop for counter from number to 1
Calculate factorial = factorial x count
If count is not 1
Print count and format with multiply
Else
Print count and format with equals
End if
End loop
Print factorial
End function
I have written this section myself however I am not sure what it means and how to do the loop for counter from number to 1 could anyone help please?
my code so far
def number_function():
factorial = 0
count = 1
number = 0
valid = False
while valid != True:
number = input("Please Enter a positive integer greater than 0 ")
if number.isnumeric():
number = int(number)
if number >= 0:
valid = True
You have to calculate the factorial and print each step of the calculs.
I understand it this way :
def number_function():
factorial = 0
count = 1
number = 0
valid = False
while valid != True:
number = input("Please Enter a positive integer greater than 0 ")
if number.isnumeric():
number = int(number)
if number >= 0:
valid = True
count = number
factorial = 1
while count >= 1:
factorial = factorial * count
if count != 1:
print (count, "*")
else:
print (count, "=")
count -= 1
print (factorial)
number_function()
Example output is:
Please Enter a positive integer greater than 0 3
3 *
2 *
1 =
6
you would want to do something like this:
you will not need a count variable, because your number will be your counter.
i added the print lines at strategic points, so you can follow, what the program does.
they are not neccessary and you can delete them afterwards.
while (number > 0): ## looping while number not reached 0
factorial = factorial * number
print (factorial)
number = number - 1 ## diminish counter variable
print (number)
print (factorial)
this will provide your loop. in its header it will test on the condition and then do your factorial equation, then diminish your number to be multiplied again, but smaller until it reaches zero.
i don't quite understand, what is meant by the rest, maybe my english skills fail me. ;)
I'm making a program that validates a credit card, by multiplying every other number in the card number by 2; after i'll add the digits multiplied by 2 to the ones not multiplied by 2. All of the double digit numbers are added by the sum of their digits, so 14 becomes 1+4. I have a photo below that explains it all. I'm making a python program that does all of the steps. I've done some code below for it, but I have no idea what to do next? Please help, and it would be greatly appreciated. The code I have returns an error anyway.
class Validator():
def __init__(self):
count = 1
self.card_li = []
while count <= 16:
try:
self.card = int(input("Enter number "+str(count)+" of your card number: "))
self.card_li.append(self.card)
#print(self.card_li)
if len(str(self.card)) > 1:
print("Only enter one number!")
count -= 1
except ValueError:
count -= 1
count += 1
self.validate()
def validate(self):
self.card_li.reverse()
#print(self.card_li)
count = 16
while count >= 16:
self.card_li[count] = self.card_li[count] * 2
count += 2
Validator()
To perform that sum:
>>> s = '4417123456789113'
>>> sum(int(c) for c in ''.join(str(int(x)*(2-i%2)) for i, x in enumerate(s)))
70
How it works
The code consists of two parts. The first part creates a string with every other number doubled:
>>> ''.join(str(int(x)*(2-i%2)) for i, x in enumerate(s))
'8427226410614818123'
For each character x in string s, this converts the character to integer, int(x) and multiplies it by either 1 or 2 depending on whether the index, i, is even or odd: (2-i%2). The resulting product is converted back to a string: str(int(x)*(2-i%2)). All the strings are then joined together.
The second part sums each digit in the string:
>>> sum(int(c) for c in '8427226410614818123')
70
You need to increment the count inside the while() loop. Also, append the user input to your card_li list after you have the if.. check. Your init method should look like:
def __init__(self):
count = 1
self.card_li = []
while count <= 16:
try:
self.card = int(input("Enter number "+str(count)+" of your card number: "))
if len(str(self.card)) > 1:
print("Only enter one number!")
self.card_li.append(self.card)
count += 1
except ValueError:
pass
self.validate()
As for your validate method, it doesn't seem complete even according to the logic you have written.
Problem statement: Write a program that reads an unspecified number of integers, determines how many positive and negative values have been read, and computes the total and average of the input values (not counting zeros). Your program ends with the input 0. Display the average as a floating-point number.
Sample output (ignore bullets, didn't know how to format text into console output):
Enter an integer, the input ends if it is 0: 1
Enter an integer, the input ends if it is 0: 2
Enter an integer, the input ends if it is 0: -1
Enter an integer, the input ends if it is 0: 3
Enter an integer, the input ends if it is 0: 0
You didn't enter any number
The number of positives is 3
The number of negatives is 1
The total is 5
The average is 1.25
Attempted solution:
def main():
i = int( input ("Enter an interger, the input ends if it is 0: "))
count_pos = 0
count_neg = 0
total = 0
if (i != 0):
while (i != 0):
if (i > 0):
count_pos += 1
elif (i < 0):
count_neg += 1
total += i
i = int( input ("Enter an interger, the input ends if it is 0: "))
count = count_pos + count_neg
average = total / count
print ("The number of positives is", count_pos)
print ("The number of negatives is", count_neg)
print ("The total is", total)
print ("The average is", float(average))
else:
print ("You didn't enter any number.")
main()
You do not need this line (which is why your error is happening):
main(i)
To continuously get user input, use an infinite loop, and test for the condition to break the loop.
while (true):
i = input("Enter an integer (0 to stop): ")
if(i == 0)
break
sum1 += i
if (i > 0):
count_pos += 1
elif (i < 0):
count_neg += 1
Then calculate and return average.
You are calling the main function with the parameter 'i', which does not exist. You can't use variables declared in a function outside of that function
Check out: Python Scopes