Search code examples
pythonmathinputsum

Limiting number of parameters to a number inputed by the user


I am trying to limit the number of parameters defined by the user to the number of inputs first defined by the user in the first input line. nexon = input('Number of exons')

(i.e If the user inputs 2, I want the user to then input values for 2 parameters, ex1 and ex2 if they input 3, I want them to input values for 3 parameters,ex1,ex2,ex3 and so on.) After inputting the parameter values, I'd like to follow the mathematical summation shown below.

Here is the code. I am struggling with why python does not request inputs for ex1, ex2, and so on when it is in an if statement. Is there a way to optimize this using a for loop?

This code only considers the possibility of 4 inputs, ideally I would like it to be able to consider any number of inputs.

The mathematical formula I am trying to incorporate is this one

nexon = input('Number of exons:')

if nexon == 1:
  ex1 = input("Exon 1 lenght:")
if nexon == 2:
  ex1 = input("Exon 1 lenght:")
  ex2 = input("Exon 2 lenght:")
if nexon == 3:
  ex1 = input("Exon 1 lenght:")
  ex2 = input("Exon 2 lenght:")
  ex3 = input("Exon 3 lenght:")
if nexon == 4:
  ex1 = input("Exon 1 lenght:")
  ex2 = input("Exon 2 lenght:")
  ex3 = input("Exon 3 lenght:")
  ex4 = input("Exon 3 lenght:")

EL1 = int(ex1)
EL2 = int(ex2)
EL3 = int(ex3)
EL4 = int(ex4)

IP1 = (EL1%3)
IP2 = (EL1+EL2)%3
IP3 = (EL1+EL2+EL3)%3
IP4 = (EL1+EL2+EL3+EL4)%3

print('exon 1 phase IP1',IP1)
print('exon 2 phase IP2',IP2)
print('exon 3 phase IP3',IP3)
print('exon 3 phase IP4',IP4)```

Solution

  • You can use a loop to ask for user input repeteadly.

    Regarding the modulo calculation, for efficiency you can use numpy:

    nexon = int(input('Number of exons:'))
    
    lengths = []
    for i in range(nexon):
        lengths.append(int(input(f"Exon {i+1} lenght:")))
    
    import numpy as np
    
    IPs = (np.array(lengths).cumsum()%3).tolist()
        
    for i, ip in enumerate(IPs, start=1):
        print(f'exon {i} phase IP{i} {ip}')
    

    example:

    Number of exons:4
    Exon 1 lenght:1
    Exon 2 lenght:3
    Exon 3 lenght:5
    Exon 4 lenght:8
    exon 1 phase IP1 1
    exon 2 phase IP2 1
    exon 3 phase IP3 0
    exon 4 phase IP4 2
    

    python only version:

    nexon = int(input('Number of exons:'))
    
    cum_lengths = []
    v = 0
    for i in range(nexon):
        cum_lengths.append(v+int(input(f"Exon {i+1} lenght:")))
        v = cum_lengths[-1]
    
    IPs = [v%3 for v in cum_lengths]
        
    for i, ip in enumerate(IPs, start=1):
        print(f'exon {i} phase IP{i} {ip}')