I'm trying to find the number of numbers divisble by 2 in 0-100, I have used a range() function and n1=n1+1 to generate 0 to 100, then with an if statement display only numbers wholely divisble by 2.
For the life of me I cannot find a way to count the number of times 0's are printed in the console, I googled count() but that seems to work for opening other files not the one you are in.
n1 = 1
for x in range(100):
dTwo = n1 % 2
if (int(dTwo) == 0):
print(n1)
n1 = n1 + 1 #generates 0 to 101
#how to I keep track of the number of 0s outputted in console after this step?
Any help would be greatly appreciated
count = 0
v = list()
for i in range(1, 101):
if i % 2 == 0:
print(i)
count += 1
v.append(i)
print(f'Number of values divisible by 2 = {count}')
print(f'Values that are divisible by 2: {v}')
As much as I get, I think you want to count number of zeros? If I am right then this is the code
count=0
while True:
y=input("Enter again : Y/N ")
if y=='Y':
n=int(input("Enter numbers as you wish :"))
if n==0:
count=count+1
elif y=='N':
break
print("Total 0's : ", count)
Related
I am trying to learn Python basics. I am designing a code that would print a triangle, code posted below. The expected output of the program must be a triangle from the right side not from the left which part of the code to modify to get the expected output.
The output of the program should not be like below
I want the output to be like this
Any help on this is highly appreciated. Thanks
while True:
n = int(input("enter a number between 0 and 10:"))
if 0 <= n <= 10:
break
print('try again')
rows = n
for num in range(rows+1):
for i in range(1, num+1):
if num % 2 == 0:
#print(end="" '#')
print('#',end="")
else:
#print(num)
print(num,end="")
print(" ")
We can use a list to create the elements (when it's an odd number just append the value in number times otherwise character '#' number times as the description said )of the triangle and then use a for loop to print them as below:
while True:
n = int(input("enter a number between 0 and 10:"))
if 0 <= n <= 10:
break
print('try again')
result = [idx*'#' if idx % 2 == 0 else f'{idx}'*idx for idx in range(1, n+1) ]
for i in range(len(result)):
print(' '*(n-i-1), result[i])
The result would be:
1
##
333
####
55555
Hope this can help you :)
Checking your code with the input (5) gives the output (1##333####55555 )
but the following code for the same input (5) gives the output (55555####333##1 )
while True:
n = int(input("enter a number between 0 and 10:"))
if 0 <= n <= 10:
break
print('try again')
rows = n
for num in range(rows, 0,-1):
for i in range(num+1, 1,-1):
if num % 2 == 0:
#print(end="" '#')
print('#',end="")
else:
#print(num)
print(num,end="")
print(" ")
Hope this answer your question
Write a python program to accept 10 numbers through command line arguments and calculate the sum of prime numbers among them.
This is my question.
I tried this
for Number in range (1, 101):
count = 0
for i in range(2, (Number//2 + 1)):
if(Number % i == 0):
count = count + 1
break
if (count == 0 and Number != 1):
print(" %d" %Number, end = ' ')
but this is naive and works only for given range. I want to input 10 numbers in command prompt and it should find the sum of prime numbers in my input. I tried using import sys and giving sys.args[input] but it is showing errors.
Can someone please help with this?I am just starting to learn coding.
Thanks in advance:)
A solution can be this:
import sys
nums = sys.argv
def with_loop():
total = 0 # to collect the prime numbers
count = 1 # a counter for the numbers that you entered
for i in range(10):
num = int(input("{}. Please enter a number: ".format(count)))
if num > 1: # if number is larger than 1, we need to check
for j in range(2, num):
if (num % j) == 0:
break
else:
total += num
elif num == 1: # 1 is a prime number
total += num
else: # otherwise the number is negative so we skip.
pass
count += 1
print("\nTotal : {}".format(total))
def with_argv(nums):
total = 0 # to collect the prime numbers
count = 1 # a counter for the numbers that you entered
for i in range(1, len(nums)):
if int(nums[i]) > 1: # if number is larger than 1, we need to check
for j in range(2, int(nums[i])):
if (int(nums[i]) % j) == 0:
break
else:
total += int(nums[i])
elif int(nums[i]) == 1: # 1 is a prime number
total += int(nums[i])
else: # otherwise the number is negative so we skip.
pass
count += 1
print("\nTotal : {}".format(total))
with_loop()
with_argv(nums)
A simple example:
sum = 0
for count in range(1,11):
sum += int(input(f'Enter number {count} : '))
print(f'Total sum : {sum}')
To solve this problem, I would first define a function that checks whether a number is prime or not. It would only return a Boolean and nothing else.
Then I would create two lists- one for storing all the numbers entered by a user and another for storing all the prime numbers among the numbers entered by the user. I would use my predefined function for this check.
When the list of prime numbers is ready, I would use the sum() method to find the sum of the items of the list viz. the primes numbers the user has entered.
Here is the code-
def isPrime(num): #defining a function to check a given number is prime
factors = []
if num == 2:
return True
else:
for i in range(1, num + 1):
if (num % i == 0):
factors.append(i)
if len(factors) == 2:
return True
else:
return False
numbers = [] #list for user entered numbers
primes = [] #list for prime numbers among them
print("Enter 10 numbers.\n")
for i in range(10):
numbers.append(int(input(f'Enter number #{i + 1}:')))
#adding user inputs to numbers list
for i in numbers: #checking if the entered numbers are prime
if isPrime(i):
primes.append(i)
print("Sum of the prime numbers enters by the user is " + str(sum(primes)))
#sum() method adds all elements in an iterable
This code will do.
Spyder uses IPython Console. That is the command line referred in the question. So, if you run the code in Spyder, the IPython console will run this program.
def per(n,steps=0):
if len (str(n))==1:
print(n)
print "TOTAL STEPS" + str(steps)
return "DONE"
steps += 1
digits = [int(i)for i in str(n)]
result = 1
for j in digits:
result *= j
print(result)
per(result,steps)
count = 0
while True:
print count
count += 1
str(wantedresult) == 12
str(steps) >= 11
if str(steps) == str(wantedresult)
print str(n)
break
I am noob.
I have another encoded and working code in my pockets(metaphorically) but not in a loop
so i wanted my results like this example in my other code is this
if my number is 277777788888899 it has an output of this
4996238671872
438939648
4478976
338688
27648
2688
768
336
54
20
0
0
TOTAL STEPS11
ummm you might need this
my error in the first code is
File "source_file.py", line 21
if str(steps) == str(wantedresult)
^
SyntaxError: invalid syntax
I think what you're trying to accomplish is to find the smallest number with a persistance of wantedresult by brute forcing all the number one by one? If so, here's something that does not differ too much from your first version:
def per(n,steps=0,display=False):
# display the number at each iteration
if display:
print(n)
if len(str(n)) > 1:
steps += 1
digits = [int(i)for i in str(n)]
result = 1
for j in digits:
result *= j
steps = per(result,steps,display)
return steps
wantedresult = 6
persistance = 0
count = 0
while True:
count += 1
persistance = per(count)
if persistance == wantedresult:
print('The smallest number with a persistance of', wantedresult, 'is', count)
per(count,display=True) # display the iterations for this number
print('TOTAL STEPS', wantedresult)
break
However it is suitable only for small persistance number and it might take a while if you want to find 277777788888899 with this approach.
BTW the syntax error you got is because you forgot the colon after the if statement.
Hope it helped.
for homework in an introductory python class, one of the questions is to count the number of even numbers in n. here's my code so far:
def num_even_digits(n):
i=0
count = 0
while i < n:
i+=1
if n%2==0:
count += 1
return count
print(num_even_digits(123456))
Pythonic answer:
def num_even_digits(x):
return len([ y for y in str(x) if int(y) % 2 == 0])
print(num_even_digits(123456))
Disclaimer: I recognized that, for an introductory Python class, my answer may not be appropriate.
you are comparing the whole number every time. you need to convert it to a string and then loop over every number in that string of numbers, cast it back to an integer and see if its remainder is 0
def num_even_digits(numbers):
count = 0
numbers = str(numbers)
for number in numbers:
try:
number = int(number)
except ValueError:
continue
if number % 2 == 0:
count += 1
return count
print(num_even_digits(123456))
if you want to actually loop through every possible number in the range of 0 to your large number you can do this.
def num_even_digits(numbers):
count = 0
for number in range(0, numbers):
if number % 2 == 0:
count += 1
return count
print(num_even_digits(10))
problems with your current function:
def num_even_digits(n): # n is not descriptive, try to make your variable names understandable
i=0
count = 0
while i < n: # looping over every number from 0 to one hundred twenty three thousand four hundred and fifty six.
i+=1
if n%2==0: # n hasn't changed so this is always going to be true
count += 1
return count
print(num_even_digits(123456))
I have the following assignment:
In this chapter you saw an example of how to write an algorithm that determines whether
a number is even or odd. Write a program that generates 100 random numbers, and keeps
a count of how many of those random numbers are even and how many are odd.
This is how far I've been able to get, I can get the 100 numbers, but I can't figure out how to total up the odd and evens. This is supposed to include a value returning boolean function as well.
All we're allowed to use is loops, if-elif-else, functions, and other basic things.
import random
NUMBER_LIST = [random.randint(0,1000)]
def main():
for numbers in range(100):
number = print(NUMBER_LIST)
number
is_even(number)
print('The total amount of even numbers is', even_count)
print('The total amount of odd numbers is', 100 - even_count)
def is_even(number):
even_count = 0
for number in NUMBERS_LIST:
if (number % 2):
even_count += 1
return even_count
main()
EDIT:
I'm not supposed to use a List, so if theres a way to do it without, let me know!
import random
def main():
numberList = [] # create an empty list, to add 100 random ints to
for i in range(100):
numberList.append(random.randint(1,1000)) # add a random int
# now, numberList has 100 random numbers in it
# keep track of how many odd numbers
oddCount = 0
# loop through numberList
for number in numberList:
if number%2 == 1: # number is odd
oddCount += 1
evenCount = 100 - oddCount # if a number is not odd, it is not even
print("There are", oddCount, "odd numbers, and", evenCount, "even numbers")
Okay, now that we have that hard-coded version, let's try a more flexible way that allows you to specify as many things as possible:
def main(numNumbers, smallestNumber, biggestNumber):
numberList = []
for i in range(numNumbers):
numberList.append(random.randint(smallestNumber, biggestNumber))
oddCount = 0
for number in numberList:
if number%2: # oh look, I didn't have to do the `== 1` part
oddCount += 1
evenCount = numNumbers - oddCount
print("There are", oddCount, "odd numbers, and", evenCount, "even numbers")
import random
NUMBER_LIST = [random.randint(0,1000)]
even = 0;
odd = 0;
for numbers in range(100):
if (numbers%2 == 1):
odd = odd+1
if (numbers%2 == 0):
even = even+1
print('number of evens is: ',even)
print('number of odds is: ',odd)
So you can just do this sort of thing.
from random import randrange
even = 0
for i in range(100):
num = randrange(1000)
if num % 2 == 0:
even += 1
print('There were {0} even numbers and {1} odd numbers.'.format(even, 100-even))
You can do this without a list, but let's do that since your problem may require so.
First of all, note that your code just creates a list with one random number inside it. If you want to populate the list with 100 random numbers, you must do something similar to this:
NUMBER_LIST = []
i = 0
while i < 100:
number = random.randint(0, 1000)
NUMBER_LIST.append(number)
i += 1
Then, you check if the number is even, with number % 2 == 0 (That is, the remainder of the division of number by 2 is 0. this will return either true or false) and increment the respective counter:
NUMBER_LIST = []
# initialize both counters
evens = 0
odds = 0
i = 0
while i < 100:
number = random.randint(0, 1000)
NUMBER_LIST.append(number)
if number % 2 == 0:
evens += 1
else:
odds += 1
i += 1
Then, you just need to print the counts:
print("The number of even numbers is: " + evens)
print("The number of odd numbers is: " + odds)
The full code would then be:
import random
NUMBER_LIST = []
evens = 0
odds = 0
i = 0
while i < 100:
number = random.randint(0, 1000)
NUMBER_LIST.append(number)
if number % 2 == 0:
evens += 1
else:
odds += 1
i += 1
print("The numbers were: " + str(NUMBER_LIST))
print("The number of even numbers is: " + evens)
print("The number of odd numbers is: " + odds)
And without the list:
import random
evens = 0
odds = 0
i = 0
while i < 100:
number = random.randint(0, 1000)
if number % 2 == 0:
evens += 1
else:
odds += 1
i += 1
print("The number of even numbers is: " + evens)
print("The number of odd numbers is: " + odds)
#!/usr/bin/env python3
import random
def main(n=100):
NUMBER_LIST = [random.randint(0,1000) for x in range(0,n)]
odds = len(list(filter(lambda x: x % 2, NUMBER_LIST)))
print("Odd Numbers: {}\nEven Numbers: {}".format(odds, n-odds))
if __name__ == "__main__":
main()
I am in the same class! This code worked for me.
import random
def main ():
counter = 1
even_numbers = 0
odd_numbers = 0
while counter < 101:
a = random.randint(1,100)
if a % 2 == 0:
even_numbers += 1
else:
odd_numbers += 1
counter += 1
if counter == 101 :
reveal_total(even_numbers, odd_numbers)
def reveal_total(even_numbers, odd_numbers):
print("This many evens : ", even_numbers)
print("This many odds : ", odd_numbers)
main()