Def is repeating when variables are called outside function

huangapple go评论68阅读模式
英文:

Def is repeating when variables are called outside function

问题

I am trying to allow a user to first select if they want to define their name, then outputting either their chosen name or a randomly selected name.
我正在尝试允许用户首先选择是否要定义他们的名字,然后输出他们选择的名字或随机选择的名字。

I can play with the positioning of the inputs to either get the function to work fine with n or y but not both.
我可以调整输入的位置,要么使函数在选择"n"或"y"时正常工作,但不能同时正常工作。

I want to call the username later on, and when I do so it loops back to ask the user input again.
我想稍后调用用户名,但当我这样做时,它会循环回来再次询问用户输入。

import random

rando_username = ['Yoda', 'Han', 'Luke', 'General Kenobi', 'Mace Windu', 'Padme', 'Anakin', 'Jar Jar Binks']
random_username = random.choice(rando_username)

user_name_choice = input('Would you like to choose your own name for the duel? y/n')

user_choice = input('What shall we call you?')

def username():
    if user_name_choice == 'y':
        username = user_choice
    else:
        username = random_username
    return username

rando_opponent = ['Darth Vader', 'Darth Sidious', 'Darth Maul', 'Kylo Ren', 'Jabba the Hutt', 'Moff Gideon', 'Jango Fett', 'General Grievous']
random_opponent = random.choice(rando_opponent)

opponent_name_choice = input('Hello there, {}! Would you like to name your enemy? y/n'.format(username()))

opponent_choice = input('What shall we call your enemy?')

def opponent_name():
    if opponent_name_choice == 'y':
        opponent_name = opponent_choice  
    else:
         opponent_name = random_opponent
    return opponent_name

print ('Excellent choice {}, your opponent is {}!'.format(username(), opponent_name()))
英文:

I am trying to allow a user to first select if they want to define their name, then outputting either their chosen name or a randomly selected name.
I can play with the positioning of the inputs to either get the function to work fine with n or y but not both.

I want to call the username later on, and when I do so it loops back to ask the user input again.

import random

rando_username = ['Yoda', 'Han', 'Luke', 'General Kenobi', 'Mace Windu', 'Padme', 'Anakin', 'Jar Jar Binks']
random_username = random.choice(rando_username)

user_name_choice = input('Would you like to choose your own name for the duel? y/n')

user_choice = input('What shall we call you?')

def username():
    if user_name_choice == 'y':
        username = user_choice
    else:
        username = random_username
    return username

rando_opponent = ['Darth Vader', 'Darth Sidious', 'Darth Maul', 'Kylo Ren', 'Jabba the Hutt', 'Moff Gideon', 'Jango Fett', 'General Grievous']
random_opponent = random.choice(rando_opponent)

opponent_name_choice = input('Hello there, {}! Would you like to name your enemy? y/n'.format(username()))

opponent_choice = input('What shall we call your enemy?')

def opponent_name():
    if opponent_name_choice == 'y':
        opponent_name = opponent_choice  
    else:
         opponent_name = random_opponent
    return opponent_name

print ('Excellent choice {}, your opponent is {}!'.format(username(), opponent_name()))

答案1

得分: 1

你两次调用了 username。尝试将 username 的值保存到一个变量中。

将用户名(和对手的名字)保存到一个变量中。同时,将 input('What shall we call you?') 放在 username 函数的 if user_name_choice == 'y': 块中,这样只有在用户想要选择自己的名字时才会调用它(对于对手的名字也是同样的情况):

import random

rando_username = ['Yoda', 'Han', 'Luke', 'General Kenobi', 'Mace Windu', 'Padme', 'Anakin', 'Jar Jar Binks']
user_name_choice = input('Would you like to choose your own name for the duel? y/n')

def username():
    if user_name_choice == 'y':
        username = input('What shall we call you?')
    else:
        username = random.choice(rando_username)
    return username

name = username()

rando_opponent = ['Darth Vader', 'Darth Sidious', 'Darth Maul', 'Kylo Ren', 'Jabba the Hutt', 'Moff Gideon', 'Jango Fett', 'General Grievous']
opponent_name_choice = input('Hello there, {}! Would you like to name your enemy? y/n'.format(name))

def opponent_name():
    if opponent_name_choice == 'y':
        opponent_name = input('What shall we call your enemy?')
    else:
         opponent_name = random.choice(rando_opponent)
    return opponent_name

print('Excellent choice {}, your opponent is {}!'.format(name, opponent_name()))

一个可能的输出:

Would you like to choose your own name for the duel? y/n
Hello there, Jar Jar Binks! Would you like to name your enemy? y/n
Excellent choice Jar Jar Binks, your opponent is Darth Vader!

(请注意,在这个示例中,这些函数实际上不再是必需的,但我保留它们以防您仍然需要它们)

英文:

You're calling username twice. Try saving username's value to a variable.

Save the username (and opponent name) to a variable. Also put the input('What shall we call you?') in the username function's if user_name_choice == 'y': block, so that it is only called if the the person wants to choose their own name (same goes for the opponent name bit):

import random

rando_username = ['Yoda', 'Han', 'Luke', 'General Kenobi', 'Mace Windu', 'Padme', 'Anakin', 'Jar Jar Binks']
user_name_choice = input('Would you like to choose your own name for the duel? y/n')

def username():
    if user_name_choice == 'y':
        username = input('What shall we call you?')
    else:
        username = random.choice(rando_username)
    return username

name = username()

rando_opponent = ['Darth Vader', 'Darth Sidious', 'Darth Maul', 'Kylo Ren', 'Jabba the Hutt', 'Moff Gideon', 'Jango Fett', 'General Grievous']
opponent_name_choice = input('Hello there, {}! Would you like to name your enemy? y/n'.format(name))


def opponent_name():
    if opponent_name_choice == 'y':
        opponent_name = input('What shall we call your enemy?')
    else:
         opponent_name = random.choice(rando_opponent)
    return opponent_name

print ('Excellent choice {}, your opponent is {}!'.format(name, opponent_name()))

A possible output:

Would you like to choose your own name for the duel? y/nn
Hello there, Jar Jar Binks! Would you like to name your enemy? y/nn
Excellent choice Jar Jar Binks, your opponent is Darth Vader!

(Note that in this example the functions are no longer really necessary, but I left them in case you still need them)

答案2

得分: 0

以下是已翻译好的内容:

  • 首先,请注意,usernameopponent_name 两个方法实际上执行相同的操作:如果 _choice 变量等于 y,它们会返回输入的名称,否则它们将从预定义列表中随机选择一个值。你可以将它们合并成一个方法,但我们暂时不讨论这个问题。
  • 你总是设置 random_usernamerandom_opponent,即使不需要 - 即当 _choice 等于 y 时 - 显然,你可以在那里节省一些工作,
  • 在你的代码中,你利用了 input 方法的同步性质:理论上,你甚至可以不将 usernameopponent_name 写成方法,而是可以将所有内容放在一个单块/顺序代码中。
  • 请注意,每次你使用 () 时,你都在调用方法:这可能会在某些情况下产生不希望的效果。

鉴于这个背景,我已经重新组织了你的代码:

import random

# 可用的用户名选项列表
random_username = ['Yoda', 'Han', 'Luke', 'General Kenobi', 'Mace Windu', 'Padme', 'Anakin', 'Jar Jar Binks']

# 可用的对手选项列表
random_opponent = ['Darth Vader', 'Darth Sidious', 'Darth Maul', 'Kylo Ren', 'Jabba the Hutt', 'Moff Gideon', 'Jango Fett', 'General Grievous']

def choose_name(your_choice, available_options, you_or_your_enemy):
    if your_choice == 'y':
        return input(f'What shall we call {you_or_your_enemy}? ')
    else:
        return random.choice(available_options)
    
if __name__ == "__main__":
    user_name_choice = input('Would you like to choose your own name for the duel [y/n]? ')
    username = choose_name(user_name_choice, random_username, "you")
    
    opponent_name_choice = input(f'Hello there, {username}! Would you like to name your enemy [y/n]? ')
    opponent_name = choose_name(opponent_name_choice, random_opponent, "your enemy")
    
    print (f'Excellent choice {username}, your opponent is {opponent_name}!')
英文:

There a few things that I would highlight regarding your code:

  • First of all, note that the two methods username and opponent_name do exactly the same thing: they return an entered name if the _choice variables are equal to y, otherwise they will pick a random value from a prefined list. You should collapse them in one method, but let's not go there for now.
  • You are always setting a random_username and random_opponent, even when is not needed - i.e. when _choice is equal to y - clearly, you could save some work there,
  • In your code, you are taking advantage of the synchronous nature of the input method: in theory, you could even avoid writing username and opponent_name as method, but you could have everything in a monolitic/sequential code
  • Note that everytime you are using the () you are calling the method: this could have undesired effects in some situations.

Given this background, I have reorganized your code:

import random

# List of username options
random_username = ['Yoda', 'Han', 'Luke', 'General Kenobi', 'Mace Windu', 'Padme', 'Anakin', 'Jar Jar Binks']

# List of opponents options
random_opponent = ['Darth Vader', 'Darth Sidious', 'Darth Maul', 'Kylo Ren', 'Jabba the Hutt', 'Moff Gideon', 'Jango Fett', 'General Grievous']

def username(user_choice):
    if user_choice == 'y':
        username = input('What shall we call you?')
    else:
        # username random selection happens only if needed
        username = random.choice(random_username)
    return username

def opponent_name(opponent_choice):
    if opponent_choice == 'y':
        opponent_name = input('What shall we call your enemy?') 
    else:
        # opponent name random selection happens only if needed
        opponent_name = random.choice(random_opponent)
    return opponent_name
    
if __name__ == "__main__":
    user_name_choice = input('Would you like to choose your own name for the duel [y/n]? ')
    # username name method called only once and assigned to VARIABLE username
    username = username(user_name_choice)
    
    opponent_name_choice = input(f'Hello there, {username}! Would you like to name your enemy [y/n]? ')
    # opponent_name method called only once and assigned to VARIABLE opponent_name
    opponent_name = opponent_name(opponent_name)
    
    print (f'Excellent choice {username}, your opponent is {opponent_name}!')

As stressed at the first point, username and opponent_name methods do exactly the same thing - you collapse the logic as follows, for example:

def choose_name(your_choice, available_options, you_or_your_enemy):
    if your_choice == 'y':
        return input(f'What shall we call {you_or_your_enemy}? ')
    else:
        return random.choice(available_options)
    
if __name__ == "__main__":
    user_name_choice = input('Would you like to choose your own name for the duel [y/n]? ')
    username = choose_name(user_name_choice, random_username, "you")
    
    opponent_name_choice = input(f'Hello there, {username}! Would you like to name your enemy [y/n]? ')
    opponent_name = choose_name(opponent_name_choice, random_opponent, "your enemy")
    
    print (f'Excellent choice {username}, your opponent is {opponent_name}!')

huangapple
  • 本文由 发表于 2023年6月12日 06:08:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/76452700.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定