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. ;)
Related
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().
I'm currently trying to make a program which first asks the user the amount of countable integers. Then the program proceeds to ask each countable integer from the user individually and in the end, the program prints the sum of the total integers calculated.
Here is the code for my program:
amount_of_integers = int(input("How many numbers do you want to count together: "))
sum = 0
repeat_counter = 1
while repeat_counter <= amount_of_integers:
countable_integer = int(input(f"Enter the value of the number {repeat_counter}: "))
sum += countable_integer
repeat_counter += 1
print()
print("The sum of counted numbers is", sum)
And this is how it currently works:
How many numbers do you want to count together: 5
Enter the value of the number 1: 1
Enter the value of the number 2: 2
Enter the value of the number 3: 3
Enter the value of the number 4: 4
Enter the value of the number 5: 5
The value of the counted numbers is: 15
Now, here comes the tricky part: If two CONSECTUTIVE inputs are both zero (0), the program should end. How do I create a variable, which checks that the values of every CONSECTUTIVE inputs in my program are not zero? Do I need to create an another loop or what?
This is how I would want the program to work:
How many numbers do you want to count together: 5
Enter the value of the number 1: 1
Enter the value of the number 2: 0
Enter the value of the number 3: 0
Two consectutive zero's detected. The program ends.
Thanks in advance!
well let's start by breaking the problem down into it's components, you have two requirements.
sum numbers
exit if two zeros are given consecutively
you have one completed, for two consider having an if which determines whether the given value is a non zero value and if it is a zero value check it does not equal the last value.
you could modify your code as follows
amount_of_integers = int(input("How many numbers do you want to count together: "))
sum = 0
repeat_counter = 1
# last integer variable
last_integer = None
while repeat_counter <= amount_of_integers:
countable_integer = int(input(f"Enter the value of the number {repeat_counter}: "))
# if statement to validate that if the last_integer and countable_integer
# are equal and countable_integer is zero then break the loop
if countable_integer == last_integer and countable_integer == 0:
break
else:
last_integer = countable_integer
sum += countable_integer
repeat_counter += 1
print()
print("The sum of counted numbers is", sum)
In this my python program. If I enter any number starting from zero, it gives me the wrong length of that number.
num = int(input("Enter any number to find out it's length: "))
def num_counter(any_num):
""" function to count the number of int in a number """
counter = 0
while any_num > 0:
any_num = any_num // 10
counter += 1
return counter
print(num_counter(num))
Because int('01') returns 1.
input already returns a string, so you can use len to get the length of the string:
num = input("Enter any number to find out its length: ")
print(len(num))
I am trying to write as the question is stated, Write a program that accepts a positive integer from the user and print the first four multiples of that integer; Use while loop (Python)
total = 0
number = int(input("Enter integer: "))
while number <= 15:
total = total + number
print(number)
SAMPLE
Enter integer: 5
0
5
10
15
this is the example my professor wanted
This is what i have so far, but i'm a bit lost...
You should loop over a counter variable instead of a hard coded limit
counter = 1
while counter <= 4:
counter += 1
total = total + number
print(number)
The loop condition should be set on total, not number, and total should be incremented by 1, not number (assuming total is used as a loop counter):
total = 0
number = int(input("Enter integer: "))
while total <= 3:
print(total * number)
total = total + 1
Sample:
Enter integer: 5
0
5
10
15
A normal while loop that counts upto 4:
count, total = 0, 0
number = int(input("Enter integer: "))
while count < 4:
print(total)
total = total + number
count += 1
Python for loop is more pythonic than while:
number = int(input("Enter integer: "))
for i in range(4):
print(number * i)
Although you have the right idea from the example there's still a couple of things the sample is missing.
1. You don't check whether the input is positive or not
2. The while loop is dependent on knowing the input
Try the following:
# Get Input and check if it's positive
number = int(input('Enter positive integer: '))
if number <= 0:
number = int(input('Not positive integer, enter positive integer: '))
# This increments i by one each time it goes through it, until it reaches 5
i=1
while i < 5:
new_number = number*i
i = i + 1
print(new_number)
Note: This does not take into account if the input is a letter or string. If so, it'll throw an error.
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.