我复制了CS Dojo的代码,但我的不起作用。

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

I copied CS Dojo's code but mine doesn't work

问题

I'm fairly new to learning Python and I've been watching CS Dojo's tutorials for absolute beginners.
我是相对新手学Python,一直在看CS Dojo的入门教程。

There's a video about solving sample problems from CodingBat with this particular problem, "String-2 double_char" text
有一个关于解决CodingBat中的样例问题的视频,涉及到这个特定问题,名为 "String-2 double_char" text

I simply copied CS Dojo's solution in the video but mine doesn't seem to work.
我只是简单地复制了CS Dojo视频中的解决方案,但我的似乎不起作用。

Here's the problem from CodingBat: String-2 double_char
以下是CodingBat的问题:String-2 double_char

Given a string, return a string where for every char in the original, there are two chars.
给定一个字符串,返回一个字符串,其中原始字符串的每个字符都变为两个字符。

For example,
例如,

double_char('The') → 'TThhee'
double_char('AAbb') → 'AAAAbbbb'
double_char('Hi-There') → 'HHii--TThheerree'

Here's the code:
以下是代码:

def double_char(str):
    to_return = ""
    for i in (str):
        to_return += i * 2
    return to_return

When I run the code, it just returns the first character of str.
当我运行代码时,它只返回str的第一个字符。

For example,
例如,

double_char("hello") only returns 'hh' instead of 'hheelloo'
double_char("hello") 只返回 'hh' 而不是 'hheelloo'

英文:

I'm fairly new to learning Python and I've been watching CS Dojo's tutorials for absolute beginners.
There's a video about solving sample problems from CodingBat with this particular problem, "String-2 double_char" text

I simply copied CS Dojo's solution in the video but mine doesn't seem to work.

Here's the problem from CodingBat: String-2 double_char

Given a string, return a string where for every char in the original, there are two chars.

For example,

`double_char('The') → 'TThhee'

double_char('AAbb') → 'AAAAbbbb'

double_char('Hi-There') → 'HHii--TThheerree'`

Here's the code:

`def double_char(str):
    to_return = ""
    for i in (str):
     to_return += i * 2
     return to_return`

when I run the code, it just returns the first character of str.

For example,
double_char("hello") only returns 'hh' instead of 'hheelloo'

答案1

得分: 2

你在函数中只进行了一次循环后就返回了。
注意:未经测试的代码

尝试更改为

def double_char(str):
    to_return = ""
    for i in (str):
        to_return += i * 2
    return to_return
英文:

You're returning from your function after only one iteration of str
Note: Untested code

Try changing this

def double_char(str):
    to_return = ""
    for i in (str):
     to_return += i * 2
     return to_return

to

def double_char(str):
    to_return = ""
    for i in (str):
     to_return += i * 2
     return to_return

huangapple
  • 本文由 发表于 2023年6月15日 00:27:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/76475709.html
匿名

发表评论

匿名网友

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

确定