Python 2: adding integers in a FOR loop [closed] - python

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 7 years ago.
Improve this question
I am working on lab in class and came across this problem:
Write a program using a for statement as a counting loop that adds up integers that the user enters. First the program asks how many numbers will be added up. Then the program prompts the user for each number. Finally it prints the sum.
I am having a lot of trouble answering this, if someone could help me that would be great, thank you!
So far I have written this:
NumOfInt=int(raw_input("How many numbers would you like to add up?"))
for i in range(NumOfInt):

I think this is what you're asking:
Write, using a for loop, a program that will ask the user how many numbers they want to add up. Then it will ask them this amount of times for a number which will be added to a total. This will then be printed.
If this is the case, then I believe you just need to ask the user for this amount of numbers and write the for loop in a similar fashion to your's:
NumOfInt = int(input("How many numbers would you like to add up? : "))
total = 0
for i in range (NumOfInt):
newnum = int(input("Enter a number! : "))
total += newnum
print("Your total is: " + str(total))
This will add their input to the total until the amount of numbers they have input exceeds NumOfInt:
How many numbers would you like to add up? : 4
Enter a number! : 1
Enter a number! : 2
Enter a number! : 3
Enter a number! : 4
Your total is: 10
I hope this helps :)

number = int(raw_input("How many numbers?"))
tot = 0
for x in range(number):
tot += int(raw_input("Enter next number:"))
print tot

Related

How to make Python multiply user input with a given fractional number? [closed]

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 months ago.
Improve this question
I'm making a currency exchange program, but NOK (the user input in Norwegian kroner) won't multiply with 0,10 and 0,11.
NOK = input("Enter the amount you wish to convert: ")
print (f"Your choosen amount is {NOK} NOK")
print("What do you wish to convert it to?")
Question = input("EUR or USD")
if Question == "EUR":
print({NOK} * 0,10)
elif Question == "USD":
print({NOK} * 0,11)
else:
print("Please anwser 'EUR' or 'USD'")
Good to see you're taking up coding.
There are a few issues with the code you provided.
You need to indent code inside if, elif, else blocks. This means insert a tab or 4 spaces before every line inside the block.
Python uses the period for the decimal seperator, unlike the comma used in European countries.
Do not use curly brackets when referencing variables.
Your NOK input is taken as a string (text), whereas it needs to be an integer (number) to multiply it. This is done with int() around your input()
Additionally, you should not name your variables starting with capital letters as these are traditionally reserved for classes.
Try this instead:
nok = int(input("Enter the amount you wish to convert: "))
print(f"Your choosen amount is {nok} NOK")
print("What do you wish to convert it to?")
question = input("EUR or USD")
if question == "EUR":
print(nok * 0.10)
elif question == "USD":
print(nok * 0.11)
else:
print("Please anwser 'EUR' or 'USD'")
You don't need to write NOK between {} and you have to transform the answer in integer to multiple it.
NOK = int(input("Enter the amount you wish to convert: "))
print ("You choosen amount is {NOK} NOK")
print("What do you wish to convert it to?")
Question = input("EUR or USD")
if Question == "EUR":
print(NOK * 0,10)
elif Question == "USD":
print(NOK * 0,11)
else:
print("Please anwser 'EUR' or 'USD'")

How to make case insensitive comparison between a string value and input string [closed]

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 created an input() and I want user to enter specific values like kg or KG or Kg and make any other values return "invalid entry"
when I try to assign other values to the variable unit1, it is taking the last entry or it throws an error
That's my code:
weight=int(input("Enter weight: "))
unit= input("Kg or Lbs: ")
unit1= "kg"
unit2="Lbs"
if unit==unit1:
print(weight/0.45)
elif unit==unit2:
print(weight*0.45)
else:
print("invalid entry")
You should change the casing of the strings to the same. String comparisons are case sensitive, so the string Lbs is not same as lbs
str.lower() is your friend here :)
You should also check to make sure someone is entering an integer for your weight so your code doesn't crash. Try this!
while True:
try:
weight=int(input("Enter weight: "))
break
except:
print("Invalid value entered for weight")
unit= input("Kg or Lbs: ")
unit1= "kg"
unit2="lbs"
if unit.lower()==unit1:
print(weight/0.45)
elif unit.lower()==unit2:
print(weight*0.45)
else:
print("invalid entry")
You could also use string.upper() in case this suits you more

How do I run the random.randint function multiple times? [closed]

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
I'm trying to make a dice roller in Python for Warhammer 40,000, and the end goal is for the user to input their Ballistic Skill (and any modifiers), the number of attacks, their Strength, the opponent's Toughness, and other stats. The program will use these stats and complete the following.
Generate a number of random integers equal to the number the user specified as the number of attacks.
Compare these to the Ballistic Skill. Any integers that are greater than or equal to the BS are passed.
Test these against the target's Toughness (this will be summarized in a later question).
Test the successes against the target's save.
Calculate damage.
Right now, I have this smidgen of code.
ballistic: int = input("What is your Ballistic Skill? Please answer in this format: '3'.")
shots: int = input('How many shots will your weapon be firing? Answer as a number.')
print("Rolling dice to hit now. Please wait...")
hits = random.randint(1, 6)
Note the declaration of the variable "hits"- this is important.
The question is: How do I run the random.randint function a number of times equal to the variable "shots"?
Jakub pointed out that in Python a for loop is typically what you would use to repeat an operation a specified number of times. Here is a very basic implementation to give you a feel for how that works.
EDIT 1: Updated Example 1 to print hits only if the value is equal to or greater than the ballistic value.
EDIT 2: Didn't modify the code, but modified the inputs (bumped number of shots up from 10 to 20) to better illustrate the relationship between ballistics and hits.
Example 1:
import random
ballistic = int(input("Enter Ballistic Skill: "))
shot_count = int(input("Enter number of shots: "))
for shot in range(shot_count):
hits = random.randint(1, 6)
if hits >= ballistic:
print(hits)
Output:
Enter Ballistic Skill: 3
Enter number of shots: 20
3
4
5
6
5
4
5
6
4
4
3
One problem with the simple approach is that the value of hits is lost at the end of the loop. That may be okay for what you are doing, but sometimes you want to build a list of something and keep it around for use after the loop. To do that, there is a more advanced technique called list comprehension that is often used, but for illustration purposes we can just build out the example above.
Example 2:
import random
shot_count = int(input("Enter number of shots: "))
hits_list = []
for shot in range(shot_count):
hits = random.randint(1, 6)
hits_list.append(hits)
print(hits_list)
Output:
Enter number of shots: 3
[1, 4, 5]

How to calculate the sum of an input in a for loop [closed]

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
So basically I want to calculate the average of (x) test marks. So far this is what I have:
for i in range(3):
testmark = int(input("Enter one test mark: "))
print("Calculating...")
average = (testmark + testmark + testmark) / (i + 1)
print("Your average is", average, "percent.")
However, I want it so that the average variable add ALL the inputs together. Right now, I made it so that it only calculates 3. I want it something like:
for i in range(7):
testmark = int(input("Enter one test mark: "))
print("Calculating...")
average = (**[sum of all test marks]**) / (i + 1)
print("Your average is", average, "percent.")
That's a good start. However, You can do it in a better way like this:
iters = int(input("How many numbers do you have?\n"))
sum = 0
for number in range(iters):
sum += int(input("Give a number: "))
print(f"The average of those inputs is {sum/iters}") # I'm assuming you have Python >= 3.6
Lets start by taking a look at the issues you encountered and how you can address them;
for i in range(3):
testmark = int(input("Enter one test mark: "))
print("Calculating...")
average = (testmark + testmark + testmark) / (i + 1)
print("Your average is", average, "percent.")
You override testmark every iteration, meaning you only ever store ONE value
You attempt to call i outside of the for loop, which will fail if i is not defined prior
We can adjust you code to be more resilient and provide the end-user more ability to modify the functions, such as how may iterations we test and the testmarks we would like to calculate.
test_marks = []
tests = int(input('How many tests are there? '))
#How many tests are there? 5
for i in range(tests):
test_marks.append(int(input("Enter one test mark: ")))
#Enter one test mark: 5
#Enter one test mark: 10
#Enter one test mark: 56
#Enter one test mark: 99
#Enter one test mark: 1
print(f"The average test mark is: {sum(test_marks) / len(test_marks)}")
#The average test mark is: 46.5
Declare an empty list to store marks in as test_marks
Prompt the user to define the total tests being entered
Iterate over the total tests and prompt the user for a mark
Calculate and print the average (This is Python 3.6+ Syntax!)
This is a good opportunity to dive a little deeper to bolster your understanding of some core workings on Python, i have included a few links for your learning!
Iterating over lists in Python
Appending & extending lists
Python 3.6 f-strings

How to print inputs in new line [closed]

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
Hey is there a way to print inputs like this:
Input:
Enter the minimum number of feet (not less than 0):
5
Enter the maximum number of feet (not more than 99):
10
How can one do this?
Simply add a new line to the input prompt with \n (Python newline character) like this:
minFeet = input("Enter the minimum number of feet (not less than 0): \n")
maxFeet = input("Enter the maximum number of feet (not more than 99): \n")
You can just do it like this:
print("Enter the minimum number of feet (not less than 0):")
minN = input()
print("Enter the maximum number of feet (not more than 99):")
maxN = input()

Categories

Resources