Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
Instructions: Program needs to ask the user for a number. For example "5". The program outputs the number 15, as 1+2+3+4+5=15.
I am a novice and am stuck at the beginning:
n = (input("Insert a number: "))
while n != 0:
Please guide me what to do further
You can do it like this:
num = int(input("Choose a number: "))
total = sum(range(num + 1))
If you HAVE to do it using a while loop, you can do it this way:
total = 0
counter = 0
max = int(input("Choose a number: "))
while counter <= max:
total += counter
counter += 1
print(total)
n = int(input("Insert a number: "))
nums = range(1,n+1)
print sum(nums)
if you want to do the same thing with while loop:
n = int(input("Insert a number: "))
sum =0
while n>0:
sum+=n
n-=1
print sum
Maybe you can use something like this code:
try:
nr_in = int(input("Enter some number: "))
nr_out = 0
tmp = 0
while tmp < nr_in:
tmp += 1
nr_out += tmp
print(nr_out)
except:
print("This is not a number!")
This isn't the shortest and most pythonic way, but I think it might be easier to understand for you.
Hope this helps!
Do you use python 3 or 2? In python2, raw_input is recommended.
Basically all you need is to convert the string to numeric value ...
inp = input("number: ")
try:
n = int(inp)
except ValueError:
print("Please give me a number")
sys.exit(1)
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I have two functions each using a while loop. However, I need to only use one while loop. What else can I do?
def get_grades(number_of_grades):
grades = []
while len(grades) < number_of_grades:
current_grade = int(input("Please enter a student grade: "))
grades += [current_grade]
return grades
def get_highest_grade(grades):
highest_grade = grades[0]
current_grade_index = 1
while current_grade_index < len(grades):
if grades[current_grade_index] > highest_grade:
highest_grade = grades[current_grade_index]
current_grade_index = current_grade_index + 1
return highest_grade
number_of_grades = int(input("How many students are there?: "))
grades = get_grades(number_of_grades)
highest_grade = get_highest_grade(grades)
print(f"The highest grade is {highest_grade}")
Your question is unclear, you should add more content next time.
What do you mean by "fix this code"? It looks like it works as intended.
Also try to use for loops instead of while loops to avoid infinite loops.
If your goal is to have only one loop to input the grades and get the highest one, here's a solution :
def get_highest_grade(number_of_grades) :
highest_grade = 0
for i in range(number_of_grades) :
current_grade = int(input("Please enter a student grade: "))
if current_grade > highest_grade :
highest_grade = current_grade
return highest_grade
not sure what you mean that you want one while loop but you can eliminate the while loop in the second fucntion 'get_highest_grade'.
You can just use python's max() function.
def get_highest_grade(grades):
highest_grade = max(grades)
return highest_grade
Going the opposite of everyone, here is a for-loop example on the first function:
def get_grades(number_of_grades):
grades = []
for i in range(number_of_grades):
grade = int(input("Please enter a student grade: "))
grades.append(grade)
return grades
Achieves the same affect.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
number = int(input(" guess the number: "))
for number in range(0,20):
if number < 13:
print("number is smaller")
elif number > 13:
print("number is greater")
else:
print("Correct guess!!")
Why does not the code give me correct output as expected
I think you have used the variable 'number' to take input and you are using it to iterate in the for loop too. That is why it is causing error, use some other variable in the for loop.
Hope this is helpful.
Don't use the for loop, instead use a while loop.
number = int()
def check_num():
try:
number = int(input('Enter the number: '))
while number != 13:
if number < 13:
print("number is smaller")
elif number > 13:
print("number is greater")
else:
print("Correct guess!!")
number = int(input('Enter the number: '))
except ValueError:
print('Only type numbers!')
check_num()
check_num()
Output:-
Enter the number: avengers
Only type numbers!
Enter the number: 2
number is smaller
Enter the number: 23
number is greater
Enter the number: 13
First of all, you are not supposed to be using a for loop for what you want because it just changes the input number. Here is the easy fix with random numbers:
import random
start_of_range = 0 # Number will be random number between these
end_of_range = 100
number_to_guess = random.randint(start_of_range, end_of_range)
while True:
try:
number = int(input("Guess the number: "))
except:
print("Enter a valid number")
continue
if number == number_to_guess:
print("Correct Guess")
break
elif number < number_to_guess:
print("Number is less")
else:
print("Number is more")
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I am trying to make it so that the user can input as many positive numbers as they want but when a negative is inputted it ends the loop and outputs the largest number inputted.
This is what I have so far
num = int(input("Enter a number: "))
while (num >= 0):
num = int(input("Enter a number: "))
if (num < 0):
print("Largest number entered: " + str(num))
Like that i guess
maxnum = int(input("Enter a number: "))
while True:
num = int(input("Enter a number: "))
if num < 0: break
maxnum = num if num > maxnum else num
if (num < 0):
print("Largest number entered: " + str(maxnum))
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
It's my 2nd week in programming in Python and have never programmed anything before. appreciate step by step.
I don't know where to start.
try:
count = 0
while True:
user = int(input('Insert Number: '))
count += user
if user == 0:
break
print(count)
except ValueError:
print('Please Insert Numbers Only!')
Here a start, use a while loop for the input. I'll leave the summation part for you unless you need further help:
cc = int(input("Enter an integer to sum. Press 0 to to end and start the summation:"))
while cc != 0:
cc = int(input("Enter an integer to sum. Press 0 to to end and start the summation:"))
def is_int(num):
try:
return int(num)
except:
return False
total = 0
while True:
in_user = is_int(input("input integer: "))
if in_user is not False:
total += in_user
if in_user is 0:
break
print(total)
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I'm just starting to learn Python and have a question regarding an exercise that came up in the textbook I'm reading.
I found a solution that does function, but I'm wondering if there is a simpler/recommended solution?
Problem:
numXs = int(input('How many times should I print the letter X? '))
toPrint = ' '
#concatenate X to print numXs times print(toPrint)
My solution:
numXs = int(input('How many times should I print the letter X? '))
toPrint = ''
while (toPrint == ''):
if numXs == 0:
numXs = int(input('Enter an integer != 0 '))
else:
toPrint = abs(numXs) * 'X'
print(toPrint)
I'd suggest you get all your data checking and correction handled up front, so your actual algorithm can be much simpler:
numXs = 0
while numXs <= 0:
numXs = int(input('How many times should I print the letter X? '))
if numXs <= 0:
print('Enter an integer > 0')
print('X' * numXs)
A simple solution would be
try:
print("x" * int(input("how many times?")))
except:
print("you entered an invalid number")
If you want a zero or negative check
try:
num = int(input("how many times?"))
if num > 0:
print("x" * num)
else:
print("need a positive integer")
except:
print("not a number")
If you want this to happen forever, just wrap it in a while loop
while True:
#code above
You are not handling wrong conversions (input of "Eight") - so you could shorten it to:
print(abs(int(input("How many?")))*"X") #loosing the ability to "requery" on 0
Same functionality:
numXs = abs(int(input('How many times should I print the letter X? ')))
while not numXs: # 0 is considered FALSE
numXs = abs(int(input('Enter an integer != 0 ')))
print(numXs * 'X')
Safer:
def getInt(msg, errorMsg):
'''Function asks with _msg_ for an input, if convertible to int returs
the number as int. Else keeps repeating to ask with _errorMsg_ until
an int can be returned'''
i = input(msg)
while not i.isdigit():
i = input(errorMsg)
return int(i)
I am using isdigit() to decide if the input is a number we can use. You could also do try: and except: around the int(yourInput) so you can catch inputs that are not conversible to integers:
def getIntWithTryExcept(msg, errorMsg):
'''Function asks with _msg_ for an input, if convertible to int returs
the number as int. Else keeps repeating to ask with _errorMsg_ until
an int can be returned'''
i = input(msg) # use 1st input message
num = 0
try:
num = int(i) # try convert, if not possible except: will happen
except:
while not num: # repeat with 2nd message till ok
i = input(errorMsg)
try:
num = int(i)
except: # do nothing, while is still True so it repeats
pass
return int(i) # return the number