How to only show the final result after adding or multiplying all natural numbers - python

It has been a week since I started to self-study python and I tried making a program that adds or multiplies all natural numbers and the problem is I want to only show the final result of all the sum or product of all natural numbers. How do I do it?
repeat = 'y'
a=0
while repeat.lower() == 'y':
result = 0
choice = 0
i=0
product = 1
num = int(input("Enter the value of n: "))
if num < 1 or num > 100 :
print('must be from 1-100 only')
repeat = input("\nDo you want to try again?Y/N\n>>> ")
continue
print('1. Sum of all natural numbers')
print('2. Product of all numbers')
choice = int(input("Enter choice: "))
if choice == 1:
while(num > 0):
result += num
num -= 1
print(' ',result)
if choice ==2:
while i<num:
i=i+1
product=product*i
print(' ', product)
repeat = input("\nDo you want to try again Y/N? \n>>> ")
while repeat.lower() == 'n':
print('\nthank you')
break

The program prints you all the numbers because the print statement is in a while loop, so it gets executed with each run of the loop. Just move the print function out of the while.
if choice == 1:
while(num > 0):
result += num
num -= 1
print(' ',result)
if choice ==2:
while i<num:
i=i+1
product=product*i
print(' ', product)

You have two problems. First, your print statements that print the results need to be un-indented by one step, so they are not PART of loop, but execute AFTER the loop. Second, you need to initialize product = 1 after the if choice == 2:. As a side note, you don't need that final while loop. After you have exited the loop, just print('Thanks') and leave it at that.
So the end of the code is:
if choice == 1:
while num > 0 :
result += num
num -= 1
print(' ',result)
if choice == 2:
product = 1
while i<num:
i=i+1
product=product*i
print(' ', product)
repeat = input("\nDo you want to try again Y/N? \n>>> ")
print('thank you\n')
I presume you'll learn pretty quickly how to do those with a for loop instead of a while loop.

Related

How to loop back to the beginning in Python

I need a bit of help in finishing this code. I am stuck trying to figure out what's wrong with my code. I don't know how to loop back from the top using while loop. It also wont print the last bit. I got the prime numbers settled but I don't know how the looping back works. May you help me?
while True:
num=int(input("Enter a number:"))
no="n"
yes="y"
if num >=1:
for i in range(2, num):
if (num % i) == 0:
print(num,"is not a prime number")
break
else:
print(num,"is a prime number")
x=str(input("If you want to continue press y, n if not:"))
if x==yes:
print()
#this part I don't know how to loop back to the start
elif x==no:
print("Okay")
#and also the loop won't stop and print the text up there^^^ when I choose n
put the if in the while loop only, and break out of the while loop if no
while True:
...
x=str(input("If you want to continue press y, n if not:"))
if x=="no":
print("Okay")
break
If you want this to repeat infinitely, your code structure might look like this:
while True: # The outer while loop, only ends when the player says "n"
while True:
# This is where you get the prime nums, paste the code for that here
if x == "n":
break # This method will only stop the loop if the input is "no", else it keeps looping forever
Or, more simply, you can do this in just one loop. The structure would be like this:
while True:
# Get if the num is prime, paste the code for that
if x == "n":
break
Possible solution if the following:
def is_prime(num):
if num <= 1:
return False
if num % 2 == 0:
return num == 2
d = 3
while d * d <= num and num % d != 0:
d += 2
return d * d > num
while True:
num=int(input("Enter a number: "))
if is_prime(num):
print(f'{num} is a prime number')
else:
print(f'{num} is not a prime number')
x = str(input("If you want to continue enter Y, or N if not: ")).lower()
if x == 'y':
print("let's start over...\n")
elif x == 'n':
print("Okay, see you")
break
Returns:
You can use code like this. In my opinion function more usefull for check prime numbers.
def is_prime(x):
for d in range(2, int(x**0.5)+1):
if x % d == 0:
return False
return x > 1
no, yes = "n", "y"
x = yes
while x == yes:
num=int(input("Enter a number:"))
if is_prime(num):
print(num,"is a prime number")
else:
print(num,"is not a prime number")
x = input("If you want to continue press y, n if not:")
print("Okay")

How do I get Python to print from 1 to user input?

I'm trying to solve the scenario with these conditions:
Ask the user to enter a number
Count up from 1 to the number that the user has entered, displaying each number on its own line if it is an odd number. If it is an even number, do not display the number.
If the user enters a number that is 0 or less, display error
My codes are as follows and I can't seem to satisfy the <= 0 print("error) condition:
num=int(input("Enter number: "))
for x in range(num):
if x % 2 == 0:
continue
print(x)
elif x<=0:
print("error")
Your solution will be :
num=int(input("Enter number: "))
if num <= 0:
print("Error")
else:
for i in range(1, num + 1):
if i % 2 == 0:
continue
print(i)
You need to print the error before looping from 1 to num because if the value is less the 0 then the loop won't run. I hope you understand.
You have to check the condition num <= 0 as soon as the user enters the number:
num = int(input("Enter number: "))
if num <= 0:
print("error")
else:
for x in range(num):
if x % 2 == 0:
continue
print(x)

how to add score and loop through game

import random
x = 50
score = 0
number = random.randint(1, x)
[print("This number is divisible by ", str(i)) for i in range(1, 10) if number % i == 0]
print('The largest possible number to guess is ' + str(x))
if number < x/2:
print('This number is less than ' + str(int(x/2)))
else:
print('This number is larger than ' + str(int(x/2)))
print(number)
while True:
if int(input('Guess: ')) == number:
print('You got it')
break
else:
print('Try again!')
What the code does so far is takes a random integer between 1 and whatever number I want. It tells me which numbers it is divisible by between 1-9 and also if it is bigger than half the maximum possible number. It essentially gives you a lot of info to guess.
I want to add a score aspect where after you guess the correct number, you will get 1 added to your score. Then it will loop back to the beginning, get a new number to guess and give all it's information again so you can guess. I'm trying to get the looping part but I'm really lost right now.
When your guess is correct we can add 1 to your current score and print it. You can play till you guess it right. You have to put the whole code in a while loop for looping through the game after every correct answer. You can break the loop if your score is greater than 10 and the game stops.
import random
x = 50
score = 0
while True:
if score >= 10:
break
number = random.randint(1, x)
[print("This number is divisible by ", str(i)) for i in range(1, 10) if number % i == 0]
print('The largest possible number to guess is ' + str(x))
if number < x/2:
print('This number is less than ' + str(int(x/2)))
else:
print('This number is larger than ' + str(int(x/2)))
print(number)
while True:
if int(input('Guess: ')) == number:
print('You got it')
score+=1
print('Your current score',score)
break
else:
print('Try again!')
Haven't worked with Python myself before but I assume you want to encapsulate everything inside a huge while loop and ask at the end of each iteration if you want to keep playing
Something like this (this is more pseudocode than anything, didn't even tested it)
import random
x = 50
score = 0
keepPlaying = True
while keepPlaying:
number = random.randint(1, x)
[print("This number is divisible by ", str(i)) for i in range(1, 10) if number % i == 0]
print('The largest possible number to guess is ' + str(x))
if number < x/2:
print('This number is less than ' + str(int(x/2)))
else:
print('This number is larger than ' + str(int(x/2)))
print(number)
if int(input('Guess: ')) == number:
print('You got it')
score++
break
else:
print('Try again!')
score--
if (input("do want to keep playing?")=="no")
keepPlaying = False

Adding while loop user inputs calculations to a list. Python3

I am using python3 and I have this code where I ask the user for three inputs. then I perform a calculation on them. I would like to keep adding the calculation results to a list. How to do that?
...
if choice == '1': #my fist input x
while True:
x = int(input('Please insert the number of things you consider yourself a fan of'))
if x > 0:
break
else:
print('Please insert a number higher than 0')
elif choice == '2': #my second input y
while True:
y = int(input('Please insert the number of hobbies you like to do every month'))
if y % 4 == 0:
break
else:
print('Please insert a valid number')
elif choice == '3': #my third input z
while True:
z = int(input('Please insert the number of sports you like'))
if z > 0:
break
else:
print('Please insert a number higher than 0')
elif choice == '4': #the calculation part
import math
def square_root():
c=(42 * y ** 2)/(z + 1)
nerd_score=int(x*math.sqrt(c))
return nerd_score
print('your nerd score is', square_root())
I want the loop to keep going, and each result to be added to the list. until the user exits the loop.
In my understanding, there are two problems you want to solve:
loop keep going, util user want to exit the loop
add every result to a list
Sample code is here:
def loop_calculation(choice):
# record results in list
results = []
# loop keep going, util user input choice 'x' which means exit
while choice != 'x':
if choice == '1': # my fist input x
while True:
x = int(input('Please insert the number of things you consider yourself a fan of'))
if x > 0:
break
else:
print('Please insert a number higher than 0')
elif choice == '2': # my second input y
while True:
y = int(input('Please insert the number of hobbies you like to do every month'))
if y % 4 == 0:
break
else:
print('Please insert a valid number')
elif choice == '3': # my third input z
while True:
z = int(input('Please insert the number of sports you like'))
if z > 0:
break
else:
print('Please insert a number higher than 0')
elif choice == '4': # the calculation part
import math
def square_root():
c = (42 * y ** 2) / (z + 1)
nerd_score = int(x * math.sqrt(c))
return nerd_score
result = square_root()
print('your nerd score is', result)
# add each result to list
results.append(result)
return results
Hope it will help you.

Python multiple number guessing game

I am trying to create a number guessing game with multiple numbers. The computer generates 4 random numbers between 1 and 9 and then the user has 10 chances to guess the correct numbers. I need the feedback to display as YYYY for 4 correct numbers guessed, YNNY for first and last number guessed etc. (you get the point). the code below keeps coming back saying IndexError: list index out of range.
from random import randint
guessesTaken = 0
randomNumber = []
for x in range(4):
tempNumber = randint(1, 9)
randomNumber.append(tempNumber)
Guess = []
Guess.append(list(input("Guess Number: ")))
print(randomNumber)
print(Guess)
if randomNumber[0] == Guess[0]:
print("Y")
elif randomNumber[1] == Guess[1]:
print("Y")
elif randomNumber[2] == Guess[2]:
print("Y")
elif randomNumber[3] == Guess[3]:
print("Y")
elif randomNumber[0] != Guess[0]:
print("N")
elif randomNumber[1] != Guess[1]:
print("N")
elif randomNumber[2] != Guess[2]:
print("N")
elif randomNumber[3] != Guess[3]:
print("N")
You need four guesses to match for random numbers, you can also shorted your code using a list comp:
from random import randint
guessesTaken = 0
randomNumber = []
Guess = []
for x in range(4):
tempNumber = str(randint(1, 9)) # compare string to string
randomNumber.append(tempNumber)
Guess.append(input("Guess Number: "))
print("".join(["Y" if a==b else "N" for a,b in zip(Guess,randomNumber)]))
You can also use enumerate to check elements at matching indexes:
print("".join(["Y" if randomNumber[ind]==ele else "N" for ind, ele in enumerate(Guess)]))
To give the user guesses in a loop:
from random import randint
guessesTaken = 0
randomNumber = [str(randint(1, 9)) for _ in range(4)] # create list of random nums
while guessesTaken < 10:
guesses = list(raw_input("Guess Number: ")) # create list of four digits
check = "".join(["Y" if a==b else "N" for a,b in zip(guesses,randomNumber)])
if check == "YYYY": # if check has four Y's we have a correct guess
print("Congratulations, you are correct")
break
else:
guessesTaken += 1 # else increment guess count and ask again
print(check)
Right now you're only asking the user for one guess, and appending the guess to the Guess list. So the Guess list has one element, but you're using Guess[1], Guess[2], etc., which of course results in the IndexError
I'll rearrange your code a bit, so it doesn't stray too far from what you've done.
from random import randint
guessesTaken = 0
randomNumbers = []
Guess = [] # Combine your guesses with your loop
for x in range(4):
tempNumber = randint(1, 9)
randomNumbers.append(tempNumber)
# This should be done four times too
# In Python 2, instead of this:
# Guess.append(input("Guess Number: "))
# do this:
Guess.append(int(raw_input("Guess Number: "))) # raw_input and pass to int
# in python 3, raw_input becomes input, so do this instead:
# Guess.append(int(input("Guess Number: ")))
print(randomNumbers)
print(Guess)
You can combine these in a loop to avoid the repetitive code:
if randomNumbers[0] == Guess[0]:
print("Y")
else:
print("N")
if randomNumbers[1] == Guess[1]:
print("Y")
else:
print("N")
if randomNumbers[2] == Guess[2]:
print("Y")
else:
print("N")
if randomNumbers[3] == Guess[3]:
print("Y")
else:
print("N")
Perhaps, to print your desired result e.g. YNNY, like this:
result = []
for index in range(4):
if randomNumbers[index] == Guess[index]:
result.append("Y")
else:
result.append("N")
print(''.join(result))
If you want terser code use Python's ternary operation:
result = []
for index in range(4):
result.append("Y" if randomNumbers[index] == Guess[index] else "N")
print(''.join(result))
Or use the fact that True == 1 and False == 0 as indexes:
result = []
for index in range(4):
result.append("NY"[randomNumbers[index] == Guess[index]])
print(''.join(result))

Categories