Python Forum
Assign the sum of 2 consecutive numbers in a list to a varibale
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Assign the sum of 2 consecutive numbers in a list to a varibale
#1
import random

no_questions = int(input("Enter the no of questions "))

questions = []
for i in range(0,no_questions*2):
    n = random.randrange(0,10)
    questions.append(n)

def pairwise(iterable):
    a = iter(iterable)
    return zip(a, a)

for x, y in pairwise(questions):
   input ("%d + %d " % (x, y))
The output will ask to enter the value of x + y, how can I assign the answer of each question to different variables
Reply
#2
One method is to append each answer to another list.

answers = []
for x, y in pairwise(questions):
   answers.append(input ("%d + %d " % (x, y)))
Reply
#3
(Apr-04-2020, 10:05 PM)bowlofred Wrote: One method is to append each answer to another list.

answers = []
for x, y in pairwise(questions):
   answers.append(input ("%d + %d " % (x, y)))

It just created another list of answers but how do I assign the each answer to the questions ?
Reply
#4
You'd use math. For answers[x], the questions for it were questions[2 * x] and questions[2 * x + 1].

It might be easier to keep the parts of the questions in separate lists, then you could index all of them equally.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  adding numbers in a list Nickd12 2 316 Jan-15-2021, 12:46 PM
Last Post: Serafim
  Print max numbers in a list jimmoriarty 1 406 Sep-25-2020, 07:29 AM
Last Post: DPaul
  importing a list of numbers into python script barrypyth 8 973 Aug-22-2020, 09:10 PM
Last Post: barrypyth
  Summing a list of numbers Oldman45 6 692 Jul-12-2020, 05:30 PM
Last Post: Oldman45
  How do I calculate a ratio from 2 numbers and return an equivalent list of about 1000 Pleiades 6 5,070 Jul-01-2020, 03:53 PM
Last Post: ndc85430
  Topic: “Filter numbers with a list comprehension” (PyBite #107) Drone4four 4 676 Jun-11-2020, 08:31 PM
Last Post: Drone4four
  Python Consecutive characters vijju56 4 986 Apr-22-2020, 11:03 AM
Last Post: TomToad
  creating consecutive rows PyPy 1 531 Feb-07-2020, 06:46 PM
Last Post: micseydel
  output a list of random numbers 'x' columns wide adityavpratap 4 773 Jan-13-2020, 05:32 PM
Last Post: perfringo
  Randomly assign values in List 1 to a value in List 2 Seneca260 7 1,478 Dec-16-2019, 12:57 PM
Last Post: BamBi25

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020