Python输入变量逗号分隔,用于循环

2024-09-24 00:36:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我的代码:

exampleA= input("Give me an ExampleA\n") #hello
exampleB = input("Give me an ExampleAB\n") #<- here you should be able to write 50, 70, 80

for x in exampleA and exampleB:
    print("nice" + exampleA) #<- i get nicehello
    print("for" + exampleB) #

所以我想对示例B中的每个元素 另一个打印,但我得到这个输出

nicehello
for50,70,80,90,20
nicehello
for50,70,80,90,20
nicehello
for50,70,80,90,20

但是我想要

nicehello
for50
nicehello
for70
nicehello
for80

顺便说一下,我是python的初学者


Tags: 代码anhelloforinputheremeprint
3条回答

正如你所说:

for x in exampleA and exampleB:
  print("nice" , exampleA) #it always print nicehello
  print("for" , exampleB) #since exampleB is 2030405060 it just prints whole data

它不会将其拆分为拆分您应该使用变量“x”

实际上,您需要拆分字符串,然后迭代字符串的元素:

exampleA= input("Give me an ExampleA\n") #hello
exampleB = input("Give me an ExampleAB\n").split(',') #<- here you should be able to write "50, 70, 80")
for x in exampleB:
    print("nice" + exampleA) #<- i get nicehello
    print("for" + x) #<- so i want for each element in exampleB 

输出:

Give me an ExampleA
Hello    
Give me an ExampleAB
12,23,34
niceHello
for12
niceHello
for23
niceHello
for34

以这种方式将代码更改为:

exampleA= input("Give me an ExampleA\n") #hello
exampleB = input("Give me an ExampleAB\n").split(',') #<- here you should be able to write 50, 70, 80

for x in exampleB:
    print("nice" + exampleA) #<- i get nicehello
    print("for" + x) #

相关问题 更多 >